UI Thread Synchronization

Source: Internet
Author: User

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 + "]";
}

}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.