Disposing ActiveX resources owned by another thread

Posted by Stefan Teitge on Stack Overflow See other posts from Stack Overflow or by Stefan Teitge
Published on 2010-06-16T08:04:46Z Indexed on 2010/06/16 8:12 UTC
Read the original article Hit count: 277

Filed under:
|
|

I've got a problem problem with threading and disposing resources.

I've got a C# Windows Forms application which runs expensive operation in a thread. This thread instantiates an ActiveX control (AxControl). This control must be disposed as it uses a high amount of memory. So I implemented a Dispose() method and even a destructor.

After the thread ends the destructor is called. This is sadly called by the UI thread. So invoking activexControl.Dispose(); fails with the message "COM object that has been separated from its underlying RCW", as the object belongs to another thread.

How to do this correctly or is it just a bad design I use?

(I stripped the code down to the minimum including removing any safety concerns.)

class Program
{
    [STAThread]
    static void Main()
    {
        // do stuff here, e.g. open a form

        new Thread(new ThreadStart(RunStuff);

        // do more stuff
    }

    private void RunStuff()
    {
        DoStuff stuff = new DoStuff();
        stuff.PerformStuff();
    }
}

class DoStuff : IDisposable
{
    private AxControl activexControl;

    DoStuff()
    {
        activexControl = new AxControl();
        activexControl.CreateControl(); // force instance
    }

    ~DoStuff()
    {
        Dispose();
    }

    public void Dispose()
    {
        activexControl.Dispose();
    }

    public void PerformStuff()
    {
        // invent perpetuum mobile here, takes time
    }
}

© Stack Overflow or respective owner

Related posts about garbage-collection

Related posts about activex