Disposing ActiveX resources owned by another thread
- by Stefan Teitge
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
}
}