none
COM object RRS feed

  • Question

  • Understanding COM Apartments is not an easy task. I read a lot on this subject but I am still not sure if what I am trying to do is legal:

    In C# I create a COM object in the main form, so the COM object is initialized in the Main Thread. Then I create 2 threads and associate them with functions that are making calls to the COM object's methods. This is a code analogy of what I am trying to say:

    namespace SharpCOMApartment 
    {  
    public partial class Form1 : Form  
    {  
    // COM object  
    ApartmentLib.ApartmentClassClass Class1 = new ApartmentLib.ApartmentClassClass();  
    public Form1()  
    {  
    InitializeComponent();  
    }  
    private void button1_Click(object sender, EventArgs e)  
    {  
    Thread t1 = new Thread(f1);  
    t1.Start();  
    Thread t2 = new Thread(f2);  
    t2.Start();  
    }  
    void f1()  
    {  
    Class1.Method1();  
    }  
    void f2()  
    {  
    Class1.Method2();  
    }
    }
    So, is this approach safe? And by safe I don't mean thread safe cause I will deal with the sinchronicity myself. Is this approach an accident waiting to happen, a possible deadlock?

    Thanks.
    • Edited by Torque153 Wednesday, July 1, 2009 7:36 AM formating code
    Wednesday, July 1, 2009 7:34 AM

Answers

  • Should be okay.  COM automatically marshals the call to the UI thread.  Doing this automatically is what apartments are all about.  Since the call gets marshaled anyway, you might feel better if you don't test something you can't change.  Use Control.Invoke or BeginInvoke in the threaded code to let .NET marshal the call.  That makes possible deadlocks much easier to see too.  Making COM calls on the thread that created the COM object is always safe.

    Hans Passant.
    • Marked as answer by Nancy Shao Wednesday, July 8, 2009 3:01 AM
    Wednesday, July 1, 2009 10:31 AM
    Moderator