Reputation: 6279
For example I use the following code:
private void startCalculcationButton_Click(object sender, EventArgs e) {
int number;
if (int.TryParse(this.numberTextBox.Text, out number)) {
this.calculationResultLabel.Text = "(computing)";
Task.Factory.StartNew(() => {
int result = LongCalculation(number);
this.calculationResultLabel.BeginInvoke(new ThreadStart(() => {
this.calculationResultLabel.Text = result.ToString();
}));
});
}
}
There I call this.calculationResultLabel.BeginInvoke(...)
to switch to the UI-Thread for setting the Result to the Label.
I could also use this.Invoke(...)
(this is the Form). Does it make a difference internally?
Upvotes: 1
Views: 333
Reputation:
Invoke on Control vs. Invoke on Form
I could also use this.Invoke(...) (this is the Form). Does it make a difference internally?
It sounds like you are asking two different things. Your title says Invoke
but your code is using BeginInvoke
but you seem to be also asking about whether to invoke on a form or control.
It makes no difference whether you xxxInvoke
to the form or a specific control. Both are UI elements and both can marshal calls for you.
If you are asking about the difference between Invoke
and BeginInvoke
, two methods that can marshal a call to the UI thread via the message pump, there is a difference between them. Invoke
can lead to thread deadlock whilst the latter won't.
Anyway, since you are using Task
and that you update the UI immediately after the long running task, you are arguably better doing:
private void startCalculcationButton_Click(object sender, EventArgs e) {
int number;
if (int.TryParse(this.numberTextBox.Text, out number))
{
this.calculationResultLabel.Text = "(computing)"; // UI thread
var result = await Task.Run(() =>
LongCalculation(number)); // threadpool thread
calculationResultLabel.Text = result.ToString(); // UI thread
}
}
No fiddly manual marshalling required via BeginInvoke
or dangerous-to-use Invoke
.
Upvotes: 1