Can a Backgroundworker have or reference an eventhandler?

  • Thread starter Thread starter Rof
  • Start date Start date
R

Rof

I have an app which has to wait for messages (using port.DataReceived)
and process them when they come in. As I expect the traffic to be
heavy, I want to do this using a Backgroundworker. Can I add an
eventhandler in "DoIt" and expect the delegate to which it points to
be called in the background?

The other obvious way to do it is to continually check
port.BytesToRead, but I'm not sure that is foolproof - VS help is less
than helpful, here.

TIA,
Peter Royle
 
Yes. Events raised by the process that's being run by the background worker
will fire properly. However, the event handler will not be running on the UI
thread, so you can't do anything in that event handler to affect the
controls of a Windows Forms front end.

A good architecture for something like this is for your worker process to
not even know that it's being run on a separate thread in a
BackgroundWorker. The simple example in MSDN help doesn't separate things
this way, but that's probably reasonable for their purposes. The way you do
this is to have the worker started from a BackgroundWorker object via
RunAsync, then for the worker to communicate with its owning object only
through events. In the event handlers, the owning object then sends messages
to the BackgroundWorker object through its ReportProgress method, which in
turn raises BackgroundWorker events ON THE UI THREAD. The UserState event
argument is how you communicate data from the worker all the way up the
chain to the UI thread.

HTH,
Tom Dacon
Dacon Software Consulting
 
Back
Top