28 August 2007

The BackgroundWorker's slip

Today I've faced a problem with the BackgroundWorker class. Or two problems..
First, the IsBackground property of its thread is set to true - that means that the thread will be terminated immediately when the process tends to close. That problem could be solved simply:

Thread.CurrentThread.IsBackground = false;

But the second.. the second is that the RunWorkerCompleted handler is called asynchronously, and will never be called if the thread is aborted due to the application's closing. That's why it is a bad idea to write to the log in such event handler - the log will never state whether the thread has been cancelled, crashed due to an error or finished successfully.

To solve these two problems I offer to implement own version of BackgroundWorker, that will have synchronous and asynchronous "OnComplete" calls, at least. And won't run background thread.

Will try to do that later and update the post.

No comments: