What happens to the data that is passed to and from a background worker?
Data is passed from the main thread to the background worker using RunWorkerAsync:
backgroundWorker.RunWorkerAsync(myData);
This is received in the DoWork event handler in the background thread:
myData = (Data)e.Argument;
After DoWork has processed the data, it returns it using e.Result:
e.Result = myData;
This is received in the RunWorkerCompleted event handler in the main thread:
myData = (Data)e.Result;
BackgroundWorker is taking care of passing the data between the threads. I am expecting to pass large amounts of data to and from a background worker so I want to know what the overhead of this transfer is, and if there is a better way of processing a large amount of in-memory objects in a background worker. I would also like to know it is possible to access the data in the background worker from the main thread in a thread-safe manner.
For reference, I am using C#, .Net 3.5 and Windows Forms.
There really is no overhead (provided
Datais a class), since only the reference is passed around. The data itself isn’t “copied” into a thread – all threads can access the data in the process (for the most part).Yes, it’s possible to access the data, but in order to do it in a thread-safe manner, you’ll need to manage the synchronization yourself. This typically requires something like a
lock, though there are many options depending on what you are trying to accomplish.