Understanding SynchronizationContext, how to access UI controls across threads in WinForm

Source: Internet
Author: User

The SynchronizationContext class is a base class that can provide a free-threaded context without synchronization. The purpose of the synchronization model implemented by this class is to enable asynchronous/synchronous operations within the common language runtime to take the correct behavior for different asynchronous models. This model also simplifies some of the requirements that managed applications must follow to work properly in different synchronization environments. Providers of synchronization models can extend this class and provide their own implementations for these methods. (from MSDN)
In short, a thread is allowed to communicate with another thread, synchronizationcontext the role of the transmitter in the communication. In addition, there is a place to be clear, not every thread attaches synchronizationcontext this object, only the UI thread is always owned.

Foreplay

Before using multi-threaded or asynchronous in WinForm to avoid "access to controls created by this thread" is to set the form Checkforillegalcrossthreadcalls to not check for thread conflicts, or detect the invokerequired?! of the control Yes, of course, no problem. (explained that the InvokeRequired property is the property that every control object has, it returns true and False when it is true, indicating that it is on top of another thread, which is required by invoke, BeginInvoke These methods to invoke the method of updating the UI object, when False, there are two cases, 1: On the current thread, you can modify the UI object by directly calling the method, 2: On a different thread, but the control or form handle does not exist. For the judgment of whether the handle exists, it can be obtained by ishandlecreated, if the handle does not exist, it is not possible to invoke invoke ... These methods, at this time you have to wait for the creation of the handle)

Once the use of asynchronous delegates is simply addictive, not a day is uncomfortable. It turned out that the SynchronizationContext class was a good thing recently. It can be encapsulated inside a form to avoid the hassle of using invokerequired to detect UI control state. Share a test process here.

Once thought that the work more than 10 years, WinForm has not learned the head. In fact, hehe, it is very difficult to make a breakthrough in a small field. To become a real expert is sloppy, really want to live to learn old.

Test code
Public partial class Form1:form {SynchronizationContext sc = null;            Public Form1 () {InitializeComponent ();            sc = synchronizationcontext.current; This.        Load + = Form1_Load;  } private void Form1_Load (object sender, EventArgs e) {thread thread = new Thread (object state)                = = {int id = Thread.CurrentThread.ManagedThreadId;                    for (int i = 0; i < i++) {Thread.Sleep (10); Sc.                Post (UpdateUI, "line " + i.tostring ());            }            }); Thread.        Start (); }/// <summary>/// this method is executed on the main u        I thread.  </summary> private void UpdateUI (object state) {int id = Thread.CurrentThread.Man            Agedthreadid; Sendlogmessage ("Updateui thrEAD: "+ id");            string text = state As String;        Sendlogmessage (text); }///<summary>///UI thread callback method, access control refresh display///</summary>//<param name= "message" & GT; message content </param> private void Logmessageback (Object message) {Rbxmessageinfo.appendtext (Dat Etime.now + "+" + message.        ToString () + Environment.NewLine); }///<summary>///To the UI thread to queue to display messages///</summary>//<param name= "message" >& lt;/param> private void Sendlogmessage (String message) {SC.        Post (logmessageback, message); }    }

The great God's encapsulation of SynchronizationContext
protected internal static System.AsyncCallback Synccallback (System.AsyncCallback callback) { System.Threading.SynchronizationContext sc = system.threading.synchronizationcontext.current;if (sc = = null) {return callback;} Return delegate (System.IAsyncResult AsyncResult) {sc. Post (Delegate (object result) {callback ((System.IAsyncResult) result);}, AsyncResult);};} protected void Dataaction (Action action) {try{action ();} catch (System.Exception ex) {Operatelog.opexcplog (string. Format ("[{0}][{1}] function operation execution exception, exception reason: {2}", action. Method.gettype (). FullName, action. Method.name, ex. Message)); System.Windows.Forms.MessageBox.Show (Eesexception.getexception (ex). Message, "Exception warning", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Hand);}}  protected void Beginaction (Methoddelegate action, object obj, params object[] args) {Eform.asyncrequest asyncrequest = new Eform.asyncrequest (action, obj, args, System.Threading.SynchronizationContext.Current); this.inasyncaction = null; This. Onbeginaction (AsynCrequest); System.Threading.ThreadPool.QueueUserWorkItem (New System.Threading.WaitCallback (this. Onwaitcallback), asyncrequest);} protected void Beginaction (object proxy, String command, params object[] args) {methoddelegate action = Fastinvoke.createm Ethoddelegate (proxy. GetType (). GetMethod (command)); Beginaction (action, proxy, args);} protected void Beginactionwithtooltip (Methoddelegate action, Object obj, String toolTip, params object[] args) { Eform.asyncrequest asyncrequest = new Eform.asyncrequest (action, obj, args, System.Threading.SynchronizationContext.Current, toolTip); this.inasyncaction = Null;this. Onbeginaction (asyncrequest); System.Threading.ThreadPool.QueueUserWorkItem (New System.Threading.WaitCallback (this. Onwaitcallback), asyncrequest);} protected void Beginactionwithtooltip (object proxy, String command, String toolTip, params object[] args) {methoddelegate Action = Fastinvoke.createmethoddelegate (proxy. GetType (). GetMethod (command)); Beginaction (Action, Proxy, new object[]{Tooltip,args});} protected virtual void Onbeginaction (Eform.asyncrequest context) {if (this.waitingForm.Visible) {throw new eesexception ("The background is executing, please wait ...");} This.waitingForm.Message = context. Tooltip;this.waitingform.show ();} protected virtual void Onendaction (Eform.asyncresponse context) {this.waitingForm.Visible = false;} private void Onwaitcallback (object state) {Eform.asyncrequest asyncrequest = (eform.asyncrequest) state;object result = Null System.Exception Exception = Null;try{result = Asyncrequest.method (Asyncrequest.obj, Asyncrequest.args);} catch (System.Exception ex) {Exception = ex;} Eform.asyncresponse state2 = new Eform.asyncresponse (Asyncrequest.method, result, Asyncrequest.args, exception); System.Threading.SynchronizationContext context = asyncrequest.context;if (context! = NULL) {context. Post (New System.Threading.SendOrPostCallback (this). Onsendorpostcallback), State2);}} private void Onsendorpostcallback (object state) {Eform.asyncresponse asyncresponse = (eform.asyncresponse) state;this. Onendaction (Asyncresponse); if (asyncresponse.exception! = null) {System.Windows.Forms.MessageBox.Show ( Eesexception.getexception (asyncresponse.exception). Message); return;} This. Onactioncomplete (asyncresponse);} protected virtual void Onactioncomplete (Eform.asyncresponse context) {}

This is an excerpt of the project inside the base class form for the encapsulation of SynchronizationContext, subclasses just use a variety of beginaction on the line, and then handle the operation of accessing the UI control in Onactioncomplete

Understanding SynchronizationContext, how to access UI controls across threads in WinForm

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.