newbie: BackgroundWorker and events

D

Dan

I have just discovered the new BackgroundWorker of VS2005 and I'm happily
using its alternative implementations for VS2003 while waiting for the .NET
2.0 release: anyway, I'd like to ask a general question about its usage. Say
I have a worker class whose time-consuming method is wrapped by a
DoWorkEventHandler delegate and added to BackgroundWorker's DoWork. This
method uses the received BackgroundWorker to show its progress percentage
and to abort processing on user request, but in its processing also fires
some events whose args include a copy of an object calculated by this
method. The UI using this worker should update its display to show all the
objects as they are calculated by the worker. To do this, the UI thread
handles the events fired by the worker, but of course these events are on
the worker thread rather than on the UI thread, so I'm back again to the
nasty duty of wrapping some complex UI calls with Invoke to avoid an
exception.

So my question is: is there a better way of handling events fired by a
background worker thread? It would be wonderful if they could somehow got
marshaled to the UI thread as for the progress percentage display with the
BackgroundWorker, without having to modify the worker class or the client...

Thanks to all!
 
D

Dan

In the meanwhile I've tried this trick, maybe someone finds it useful: let's
say my worker class declares and fires an event like:

public class MyWorker { ...
public delegate void ItemDoneEvent(object sender, ItemDoneEventArgs e);
public event ItemDoneEvent ItemDone;
.... }

In the UI I can handle this event like:

private void OnItemDone(object sender, ItemDoneEventArgs e)
{
if (InvokeRequired)
Invoke(new MyWorker.ItemDoneEvent(OnItemDone), new object[] { sender,
e });
else
{
// ...handle the event normally, it is thread-safe here...
}
}

This still requires to modify the UI code, but at least saves me from
declaring delegates and using tons of Invoke's. Any other idea?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top