Reputation: 52123
I'm trying to find a really strange bug in my application and while looking for it I've come across a doubt about how BackgroundWorker works.
If I have a code that looks like this:
var bg = new BackgroundWorker();
bg.DoWork += MyHandler;
bg.RunWorkerAsync
Is there anyway in which that would never run? What I have in mind is the bg getting out of scope and being claimed by the BG before it can actually get a chance to run.
Could that happen?
Upvotes: 0
Views: 170
Reputation: 40345
No, the fact that you called RunWorkerAsync
"queues" the work for execution on a separate thread, so there is reference to your worker aside from the one you had to it. If something is keeping a reference to the worker, then the worker will not be disposed. To be more precise: the thread instance that's executing the worker needs to have a handle to it in order to access the worker state (which prevents the worker from being disposed once it leaves your scope).
The only way for the worker to get disposed before executing is if you do something to explicitly dispose it yourself (I can't think of what that could be) or if you exit the application before the worker executes.
Upvotes: 1
Reputation: 36775
If in the next line an exception will happen, probably the DoWork will not be called. But I don't assume this is your problem. Otherwise no, RunWorkerAsnyc will trigger the execution in any way, GC will not garbage the instance also if you don't have no more reference to your BackgroundWorker.
Check the AsyncCompletedEventArgs.Error property, to see if an exception has happened in the DoWork-eventhandler.
Upvotes: 2