Hi guys, need you advice here. Have to say I’m new to Threading applications and C# in general, so may be it is really simple and just I can not see it.
I created a really simple project to show my problem (VS 2008 C# WinForm Project)
I have a 3rd party COM object which I want to run when click on a Start button. The ApartmentState of this COM object is MTA and since WinForm Thread is STA only,
I have to create a new Thread to be able to work with my COM, so here is the code.
Everything working fine and label showing the expected result, but clicking Exit killing the application:
"The memory could not be read. Click OK to terminate the program.
I think it might be a problem with thread management but I do not know exactly what is wrong.
I’m out of ideas, really appreciate your help.
I created a really simple project to show my problem (VS 2008 C# WinForm Project)
I have a 3rd party COM object which I want to run when click on a Start button. The ApartmentState of this COM object is MTA and since WinForm Thread is STA only,
I have to create a new Thread to be able to work with my COM, so here is the code.
Code:
Program.cs
public delegate void ThreadStart();
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new frmCOMNameRIC());
}
Form1.cs
public partial class frmCOMNameRIC : Form
{
public double tm=0.0;
public frmCOMNameRIC()
{
InitializeComponent();
}
private void cmdStart_Click(object sender, EventArgs e)
{
Thread t = new Thread(new ThreadStart(UseCOMNameThread));
t.SetApartmentState(ApartmentState.MTA);
t.Start(); //Start thread t
t.Join(); //Wait until thread t finishes
lblTime.Text=tm.ToString();
}
public void UseCOMNameThread(){
DateTime current;
MyCOMObject lst = new MyCOMObject();
try
{
//do the job
tm=Convert.ToDouble(result);
}
catch(Exception ex)
{
//log error message
}
System.Runtime.InteropServices.Marshal.ReleaseComObject(lst)
}
private void cmdExit_Click(object sender, EventArgs e){
this.Close();
}
"The memory could not be read. Click OK to terminate the program.
I think it might be a problem with thread management but I do not know exactly what is wrong.
I’m out of ideas, really appreciate your help.
Comment