I\'m a newbie with multithreading. I have a winform that have a label and a progress bar.
I wanna show the processing result. Firstly, I use Application.DoEven
Invoke the UI thread. For example:
void SetControlText(Control control, string text)
{
if (control.InvokeRequired)
control.Invoke(SetControlText(control, text));
else
control.Text = text;
}
Do like this, create a new thread
Thread loginThread = new Thread(new ThreadStart(DoWork));
loginThread.Start();
Inside the ThreadStart(), pass the method you want to execute. If inside this method you want to change somes controls properties then create a delegate and point it to a method inside which you will be writing the controls changed properties,
public delegate void DoWorkDelegate(ChangeControlsProperties);
and invoke the controls properties do like this, declare a method and inside it define the controls new porperties
public void UpdateForm()
{
// change controls properties over here
}
then point a delegate to the method, in this way,
InvokeUIControlDelegate invokeDelegate = new InvokeUIControlDelegate(UpdateForm);
then when you want to change the properties at any place just call this,
this.Invoke(invokeDelegate);
Hope this code snippet helps you ! :)
Cleanest way is using BackGroundWorker
as you did.
you just missed some points:
DoWork
event handler because that makes a cross thread method invokation, this should be done in ProgressChanged
event handler.BackGroundWorker
will not allow to report progress, as well as in won't allow Cancelling the operation. When you add a BackGroundWorker
to your code, you have to set the WorkerReportsProgress
property of that BackGroundWorker
to true
if you want to call the ReportProgress
method of your BackGroundWorker
.WorkerSupportsCancellation
to true and in your loop in the DoWork
event handler check the property named CancellationPending
in your BackGroundWorker
I hope I helped