views:

389

answers:

3

I know you can pass arguments through the RunWorkerAsync function call when you first start the backgroundworker, but can you pass it data after its already been started? Or would I need to create my own form of concurrency to handle passing data to it from a different thread?

+3  A: 

You'll need to add some synchronization, and have a place for the background worker to read data from.

You can't (easily) SEND data to the background worker. It's much easier to just have a place where the worker can look for data, and you can just add data to process. Just make sure to put synchronization in place on that point, since (at least) two threads will be accessing the data at potentially the same time.

Reed Copsey
Thats what I thought, is there any better producer/consumer example then Mr Skeets? http://www.yoda.arachsys.com/csharp/threads/deadlocks.shtml
SwDevMan81
His is a very clean, straitdforward option. It would be possible, under some circumstances, to use a ReaderWriterLock instead, which might be better (but only in some cases), since it wouldn't block readers. See: http://msdn.microsoft.com/en-us/library/system.threading.readerwriterlock.aspx
Reed Copsey
Great, I'll check that out and see if I can use that. Thanks
SwDevMan81
The solution from SwDevMan81, at a glance, looks wrong. I see two threads accessing the same queue simultaneously. Shouldn't enqueue and dequeue should be in critical sections?
Eyal
@Eyal: Jon Skeet's post does handle things correctly. The enqueue and dequeue calls are inside of locks [lock (listLock)], and everything works fine.
Reed Copsey
+2  A: 

There is not supported mechanism within the BackgroundWorker API to pass additional data after the task has been started.

However the worker routine is simply running on a different thread. You can pass data to that thread in the same way you would pass data between 2 arbitrary threads. A couple of quick examples on how ...

  • State change on Static variables (probably evil)
  • State change on the object initially passed down to the worker routine (still a bit evil if not properly controlled)

You should carefully consider the synchronization impact of these approaches.

JaredPar
A: 

I prefer to use a static Queue that the background thread that periodically checks for new messages. This allows the background thread to work at its own pace. You can use callback methods to signal back to the main thread. And like Reed said, use synchronization, such as a static object to lock on.

ebpower