For passing data to a BackgroundWorker
's DoWork
I use a separate wrapper class' instance:
MyParams mpar = new MyParams();
...
mpar.Par1 = par1val;
mpar.Par2 = par2val;
mpar.Par3 = par3val;
...
var worker1 = new System.ComponentModel.BackgroundWorker();
worker1.DoWork += new DoWorkEventHandler(worker1_DoWork);
worker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker1_RunWorkerCompleted);
worker1.RunWorkerAsync(mpar);
Then I can use parameters of mpar
instance in worker1_DoWork
, operating in another thread.
void worker1_DoWork(object sender, DoWorkEventArgs e)
{
//here we use mpar.Par1, mpar.Par2 and so on
}
In RunWorkerCompletedEventHandler
we do some postactions in UI thread.
My question is : Can we use in RunWorkerCompleted
handler the mpar
instance, which worked just before in DoWork
handler and can we be sure its values are the same it had in DoWork
? If not, what is the correct approach for sharing parameters for various stages of BackgroundWorker
operation?
void worker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
Dispatcher.BeginInvoke((Action)(() =>
{
//Can we use the mpar instance here?
}
));
}
You can send a parameter to the background operation using the RunWorkerAsync() method. You can receive this parameter by using the Argument property of the instance of DoWorkEventArgs in the DoWork event handler then you cast it to use it in the background operation.
BackgroundWorker makes the implementation of threads in Windows Forms. Intensive tasks need to be done on another thread so the UI does not freeze. It is necessary to post messages and update the user interface when the task is done.
RunWorkerAsync() Starts execution of a background operation. RunWorkerAsync(Object) Starts execution of a background operation.
A BackgroundWorker component executes code in a separate dedicated secondary thread. In this article, I will demonstrate how to use the BackgroundWorker component to execute a time-consuming process while the main thread is still available to the user interface.
You can assign the value of e.Result
in worker1_DoWork
static void worker1_DoWork(object sender, DoWorkEventArgs e)
{
//Do the work
//...
e.Result = new MyParams();
}
Then you can get it in the worker1_RunWorkerCompleted
in e.Result
.
If you need to pass additional result value and you don't want to put MyParams object in the worker1_DoWork: e.Result
- then you can create a small class ResultHolder
with MyParams
and MyResult
as properties and use that class to pass the result in worker1_DoWork
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With