Greetings,
I am developing some application in C#. At the moment I’m dealing with threading and I have a question that I have in my mind.
What is the difference between Invoke and BeginInvoke?
I read some thread and I found some useful information here: here
However what is the difference between Invoke and BeginInvoke in the following code:
private void ProcessRoutine()
{
for (int nValue = StartFrom; nValue <= EndTo; nValue++)
{
this.Invoke(this.MyDelegate, nValue);
//this.BeginInvoke(this.MyDelegate, nValue);
}
MessageBox.Show("Counting complete!");
}
private void MessageHandler(int progress)
{
lblStatus.Text = lblStatus.Text = "Processing item: " + progress.ToString();
progressBar1.Value = progress;
}
where MyDelegate is a reference to MessageHandler function.
I noticed that using BeginInvoke lblStatus.Text is not refreshed where using Invoke refreshes the label.
Additionally I know that Invoke waits for its execution to complete.
The most important case I’m interested in is why there is a difference in refreshing label text in this case.
With Invoke the method gets executed and the application waits for it to complete.
With BeginInvoke the method is invoked Asychnronously and the application continues to execute while the method referenced in BeginInvoke is executed.
With BeginInvoke you need to call EndInvoke to get the results of the method you executed using BeginIvnoke.
You should not update GUI components in BeginXXX methods as they are run in another thread to the GUI thread, contrary to your Invoke method. You cannot access GUI components in a different thread to the GUI thread.
Hope this helps!