Code related to UI thread synchronization commonly used in WINFORM Development
Using System;
Using System. Collections. Generic;
Using System. ComponentModel;
Using System. Data;
Using System. Drawing;
Using System. Linq;
Using System. Text;
Using System. Windows. Forms;
Using System. Threading. Tasks;
Using System. Threading;
Namespace ThreadTestApp
{
/// <Summary>
/// Thread synchronization test
/// </Summary>
Public partial class Form1: Form
{
Public Form1 ()
{
InitializeComponent ();
}
Private void btnInvoke_Click (object sender, EventArgs e)
{
// 1. Direct call
OperateUI (DoSomeThing ("direct call "));
// 2. synchronous call
Var v2 = new Task <string> () => DoSomeThing ("synchronous call "));
V2.Start ();
V2.ContinueWith (o) =>{ OperateUI (o. Result) ;}, CancellationToken. None,
TaskContinuationOptions. OnlyOnRanToCompletion, TaskScheduler. FromCurrentSynchronizationContext ());
// 3. asynchronous exception capture
Var v3 = new Task <string> () => DoSomeThing ("ThrowEx "));
V3.Start ();
V3.ContinueWith (o) =>{ OperateUI (v3.Exception. InnerExceptions [0]. Message) ;}, CancellationToken. None,
TaskContinuationOptions. OnlyOnFaulted, TaskScheduler. FromCurrentSynchronizationContext ());
// 4. Classic UI call
ThreadPool. QueueUserWorkItem (o) =>{ Classic (DoSomeThing ("Classic UI call "));});
}
Private void Classic (string v)
{
If (this. InvokeRequired) // You Need To Find A call control.
{
Action <string> a = new Action <string> (OperateUI );
This. Invoke (a, new object [] {v });
}
Else
{
OperateUI (v );
}
}
Private void OperateUI (string v)
{
TabDisplay. TabPages. Add (v );
LblDisplay. Text = v;
MessageBox. Show (v );
This. Text = v;
}
Private string DoSomeThing (string v)
{
If (v = "ThrowEx ")
Throw new Exception ("custom Exception ");
Else
Return "[" + v + "]";
}
}
}