C#: Passing data to BackgroundWorker DoWork Event

Normally, you call the RunWorkerAsync() without an argument to start the background worker. Sometimes you might want to pass some data into the DoWork() function.

All you have to do is simply do:
RunWorkerAsync(some data)

For example, the following code pass an array of string:


string[] list = {"one", "two", "three"};
MyBackgroundWorker1.RunWorkerAsync(List);

Then you have to write the receiving code in the DoWork Event function, the trick is in the DoWorkEventArgs e contains the data you passed. You simply use e.Argument, then cast the object into the original type when you passed the data.

For example: the following code receives the string[] list


private void MyBackgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
   //get the string[] that was passed by RunWorkerAsync(List)
   string[] myList = e.Argument as string[];
}

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>