brycepfrimmer
brycepfrimmer

Reputation: 51

Is it safe to run multiple DoWork functions on a single BackgroundWorker?

I'm working with an established code base and I'd like to move some of the work that's being done to a separate thread. The way the code is currently structured I'd like to do something like:

var backgroundWorker = new BackgroundWorker();
backgroundWorker.DoWork += firstFunctionToDoSomeWork;
backgroundWorker.DoWork += secondFunctionToDoSomeWork;
backgroundWorker.RunWorkerCompleted += theWorkerCompletedFunction;
backgroundWorker.RunWorkerAsync();

I would like the the two DoWork functions to run in order, the firstFunctionToDoSomeWork running and finishing before the secondFunctionToDoSomeWork starts. Is it safe to do something like this? Or will I possibly get conflicts when the two functions don't run in order? I guess what I'm wondering is how the BackgroundWorker will handle the second DoWork function.

Thanks

Upvotes: 4

Views: 1113

Answers (1)

Servy
Servy

Reputation: 203830

You should not rely on event handlers to be fired by an event in a particular order. Most implementation, in actual practice, will have a defined order (the most common of which is the order in which the handlers are added), but you cannot be sure that this is case for any particular event, and it is virtually never explicitly defined in an event's documentation, meaning that it's something that's subject to change over time.

Most events also fire their handlers sequentially, even if the order is not defined, but not all. Some even fire their handlers in parallel. You can be pretty confident that that won't happen here, but in the general case, it is something to be prepared for when writing handlers for an arbitrary event.

If it's important for you to perform these two functions sequentially then you should add one handler, and in that handler you should call these two methods:

backgroundWorker.DoWork += (s, args) => 
{
    firstFunctionToDoSomeWork(s,args);
    secondFunctionToDoSomeWork(s,args);
};

Upvotes: 3

Related Questions