Control.BeginInvoke schedules a delegate on the UI thread associated with a WinForms control. It lets background work update controls without directly touching UI state, preserving responsiveness while the event loop handles input and repainting. section 4.3 section 6.2
A typical workflow separates computation from presentation:
- Start long-running work with Thread, the thread pool, or Task.Run. section 4.3
- Call BeginInvoke when the work completes, passing a delegate that updates the control. section 6.2
- Avoid blocking or busy-waiting on the UI thread; the queued delegate may then never execute, freezing the interface or causing deadlock. section 4.3
- Prefer await when it naturally resumes on the UI thread, because it avoids much of the explicit continuation and dispatching code. section 11.1.1
Listing 11.3 UI access with ContinueWith
private void button1_Click(object sender, EventArgs ea)
{
var result = DoSomething(textBox1.Text).ContinueWith(t=>
{
label1.BeginInvoke((Action)(()=> #1
{
label1.Text = t.Result));
});
}
}
Shows the explicit WinForms continuation pattern: a thread-pool callback uses label1.BeginInvoke before assigning label1.Text. section 11.1.1
