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.
Expand|Select|Wrap|Line Numbers
- 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.