Marino Šimić
Marino Šimić

Reputation: 7342

Running a piece of code without blocking that uses a COM object created in main thread

I have a slow method that I'd like to run in a separate thread. This method uses a call on a COM object created in the main thread of the app.

Lets assume the code that is slow is this:

var bwImg = image.GetBitonalImage(); // <- slow image is a COM created in main thread
viewer.Document = bwImg; // <-- ATL control accepting the B/W COM image 

If that matters, I am doing this in a WPF application and 'viewer' is in a WinFormsHost.

I assumed that doing this would make this asynchronous and not block the running of the application:

var t = new Thread((ThreadStart)(() =>
{
    var bwImg = image.GetBitonalImage(); // <- this is in separate thread
    Dispatcher.Invoke((Action)(() =>
    {
        viewer.Document = bwImg; // <- this again on the main
    }));
}));
t.Start();

It is ok for me that the images gets shown at some later time, and I do not care how much later.

But it happens that the application is blocked in the same way. I did profiling and indeed most time is spent in GetBitonalImage, and almost none in 'viewer.Document = bwImg'.

Removing the code altogether makes the app responsive, so it's not other code fault.

There is other code later after this that uses the same image COM object (not the B/W result but the original).

Is this the correct way to do this? Can the problem be because of the COM object method call?

Upvotes: 1

Views: 197

Answers (2)

ChrisLively
ChrisLively

Reputation: 88054

Correct in this situation has a lot of different meanings. :/

Can the problem be because of the COM object method call?

Well, if you remove that call and the application runs faster then I'd say: yes..

Is this the correct way to do this?

The best answer is is a question: does it work? If so, then you are probably on the right track.

It's hard to say for sure because I have no idea what the com object does. Is it designed for single threaded operation? How is it going to behave if multiple threads create instances? In other words, is the com object itself thread safe? I imagine you'll find out the answers to that soon enough.

Now to a broader question:

Is this the correct way to handle long running asynchronous processes?

Yes.

Upvotes: 0

Michael Yoon
Michael Yoon

Reputation: 1606

Is your COM object threadsafe? If it's not, then it might be initialized in STA (single-threaded apartment) mode, which would use the STA thread to do its work. So even though you spun up a new thread, it would switch back to the STA thread, blocking your UI events. If you have control over the source for the COM library you could change those settings, as long as the code is actually threadsafe.

Edit: Found this link in the related posts section, it might be applicable to you. UI thread is blocking a background thread calling a COM object.

Upvotes: 4

Related Questions