2

I have a BackgroundWorker that calls an asynchronous method. The async method provides a callback argument to let me know it's finished.

//Bunch of stuff to prep for the call happens first
SomeAsyncMethodIn3rdPartyDll(callback);
//A few more clean up operations after the call

The problem I have is that the BackgroundWorker finishes before the callback is called and thus it is never called since the thread is dead.

My current (working) solution is to add this at the end of my DoWork method:

      while (keepAlive)
      {
        Application.DoEvents();
        System.Threading.Thread.Sleep(100);
      }

Then I simply set the value of keepAlive to false when I've received the callback.

This seems hacky, especially with the Application.DoEvents() command which is required to get the callback to fire.

So, what I want to know is: Is there a better way to keep the thread alive? Or, can I specify which messages I want to process instead of DoEvents (which does all messages)? Some other solution?

Servy
  • 202,030
  • 26
  • 332
  • 449
MikeH
  • 4,242
  • 1
  • 17
  • 32
  • Hmm, this must be a COM component to behave like this. BGW is a pretty hostile place for such components, you really should avoid it. Given that it support callbacks, the regular UI thread should already be good enough. If not then be sure to create [an STA thread](http://stackoverflow.com/a/21684059/17034) for the component so it has a happy home. Don't be in a hurry to kill it. – Hans Passant Sep 03 '15 at 18:56

1 Answers1

3

You shouldn't be using a BackroundWorker at all. A BGW is there for doing CPU bound work in another thread. You're trying to call an asynchronous operation. Just scrap the BGW entirely. Start the asynchronous operation right in the UI thread, and do whatever you need to do when that operation has finished in the callback method.

You can use the Task Parallel Library to encapsulate the asynchronous operation in a Task if you want, as, combined with the await keyword, it allows for an more powerful syntax for performing asynchronous operations, if you want.

Servy
  • 202,030
  • 26
  • 332
  • 449
  • There are a bunch of things going on to prep the call to the async method. Running those on the UI thread is not an option. I haven't dove into the Task Parallel Library too much, but, could I wrap the async call into a Task and await from my BGW thread? – MikeH Sep 03 '15 at 19:04
  • @MikeH If you're using the TPL then you don't need a BGW, you'd simply await the prep work, then await the async operation, then await the cleanup work. Without the TPL you'd run the prep work in another thread, then start the async work, then in the callback you'd start another thread to do the cleanup work. That's how asynchronous programming works. – Servy Sep 03 '15 at 19:06