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?
views:
389answers:
3You'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.
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.
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.