SynchronizationContext 类是一个基类,可提供不带同步的自由线程上下文。 此类实现的同步模型的目的是使公共语言运行库内部的异步/同步操作能够针对不同的异步模型采取正确的行为。此模型还简化了托管应用程序为在不同的同步环境下正常工作而必须遵循的一些要求。同步模型的提供程序可以扩展此类并为这些方法提供自己的实现。(来自MSDN)

  简而言之就是允许一个线程和另外一个线程进行通讯,SynchronizationContext在通讯中充当传输者的角色。另外这里有个地方需要清楚的,不是每个线程都附加SynchronizationContext这个对象,只有UI线程是一直拥有的。

  这里你可能有个问题:对于UI线程来说,是如何将SynchronizationContext这个对象附加到线程上的呢?!OK,我们先从下面的代码开始,

 
  
  1. [STAThread]  
  2.  
  3. static void Main()  
  4.  
  5. {  
  6.  
  7.     Application.EnableVisualStyles();  
  8.  
  9.     Application.SetCompatibleTextRenderingDefault(false);  
  10.  
  11.  
  12.  
  13.     // let's check the context here  
  14.  
  15.     var context = SynchronizationContext.Current;  
  16.  
  17.     if (context == null)  
  18.  
  19.         MessageBox.Show("No context for this thread");  
  20.  
  21.     else 
  22.  
  23.         MessageBox.Show("We got a context");  
  24.  
  25.  
  26.  
  27.     // create a form  
  28.  
  29.     Form1 form = new Form1();  
  30.  
  31.  
  32.  
  33.     // let's check it again after creating a form  
  34.  
  35.     context = SynchronizationContext.Current;  
  36.  
  37.  
  38.  
  39.     if (context == null)  
  40.  
  41.         MessageBox.Show("No context for this thread");  
  42.  
  43.     else 
  44.  
  45.         MessageBox.Show("We got a context");  
  46.  
  47.  
  48.  
  49.     if (context == null)  
  50.  
  51.         MessageBox.Show("No context for this thread");  
  52.  
  53.  
  54.  
  55.     Application.Run(new Form1());  
  56.  
  57. }  
  58.  

 

运行结果:
1、No context for this thread
2、We got a context
   
    从运行结果来看,在Form1 form = new Form1()之前,SynchronizationContext对象是为空,而当实例化Form1窗体后,SynchronizationContext对象就被附加到这个线程上了。所以可以得出答案了:当Control对象被创建的同时,SynchronizationContext对象也会被创建并附加到线程上。

    好的,我们既然已经基本了解了SynchronizationContext,接下来的事情就是使用它了!

如何使用SynchronizationContext
--------------------------------------------------------------------------------
  应用程序有两个线程:线程A和线程B,不过线程B比较特殊,它属于UI线程,当这两个线程同时运行的时候,线程A有个需求:"修改UI对象的属性",这时候如果你是线程A,你会如何去完成需求呢?!

第一种方式:   

    在线程A上面直接去操作UI对象,这是线程B说:"线程A,你真xx,你不知道我的特殊嘛!",然后直接抛给线程A一个异常信息,线程A得到异常后,一脸的无辜和无奈.....!

第二种方式:

  InvokeRequired?!是的,当然没问题。(解释下,InvokeRequired属性是每个Control对象都具有的属性,它会返回true和false,当是true的时候,表示可以去修改UI对象,反之则不允许。通过InvokeRequired的实现方式如下:

 
  
  1. using System;  
  2.  
  3. using System.Drawing;  
  4.  
  5. using System.Windows.Forms;  
  6.  
  7. using System.Threading;  
  8.  
  9.  
  10.  
  11.   public class MyFormControl : Form  
  12.  
  13.   {  
  14.  
  15.       public delegate void AddListItem(String myString);  
  16.  
  17.       public AddListItem myDelegate;  
  18.  
  19.       private Button myButton;  
  20.  
  21.       private Thread myThread;  
  22.  
  23.       private ListBox myListBox;  
  24.  
  25.       public MyFormControl()  
  26.  
  27.       {  
  28.  
  29.         myButton = new Button();  
  30.  
  31.         myListBox = new ListBox();  
  32.  
  33.         myButton.Location = new Point(72, 160);  
  34.  
  35.         myButton.Size = new Size(152, 32);  
  36.  
  37.         myButton.TabIndex = 1;  
  38.  
  39.         myButton.Text = "Add items in list box";  
  40.  
  41.         myButton.Click += new EventHandler(Button_Click);  
  42.  
  43.         myListBox.Location = new Point(48, 32);  
  44.  
  45.         myListBox.Name = "myListBox";  
  46.  
  47.         myListBox.Size = new Size(200, 95);  
  48.  
  49.         myListBox.TabIndex = 2;  
  50.  
  51.         ClientSize = new Size(292, 273);  
  52.  
  53.         Controls.AddRange(new Control[] {myListBox,myButton});  
  54.  
  55.         Text = " 'Control_Invoke' example ";  
  56.  
  57.         myDelegate = new AddListItem(AddListItemMethod);  
  58.  
  59.       }  
  60.  
  61.       static void Main()  
  62.  
  63.       {  
  64.  
  65.         MyFormControl myForm = new MyFormControl();  
  66.  
  67.         myForm.ShowDialog();  
  68.  
  69.       }  
  70.  
  71.       public void AddListItemMethod(String myString)  
  72.  
  73.       {  
  74.  
  75.             myListBox.Items.Add(myString);  
  76.  
  77.       }  
  78.  
  79.       private void Button_Click(object sender, EventArgs e)  
  80.  
  81.       {  
  82.  
  83.         myThread = new Thread(new ThreadStart(ThreadFunction));  
  84.  
  85.         myThread.Start();  
  86.  
  87.       }  
  88.  
  89.       private void ThreadFunction()  
  90.  
  91.       {  
  92.  
  93.         MyThreadClass myThreadClassObject  = new MyThreadClass(this);  
  94.  
  95.         myThreadClassObject.Run();  
  96.  
  97.       }  
  98.  
  99.   }  
  100.  
  101.   public class MyThreadClass  
  102.  
  103.   {  
  104.  
  105.       MyFormControl myFormControl1;  
  106.  
  107.       public MyThreadClass(MyFormControl myForm)  
  108.  
  109.       {  
  110.  
  111.         myFormControl1 = myForm;  
  112.  
  113.       }  
  114.  
  115.       String myString;  
  116.  
  117.  
  118.  
  119.       public void Run()  
  120.  
  121.       {  
  122.  
  123.         for (int i = 1; i <= 5; i++)  
  124.  
  125.         {  
  126.  
  127.             myString = "Step number " + i.ToString() + " executed";  
  128.  
  129.             Thread.Sleep(400);  
  130.  
  131.             // Execute the specified delegate on the thread that owns  
  132.  
  133.             // 'myFormControl1' control's underlying window handle with  
  134.  
  135.             // the specified list of arguments.  
  136.  
  137.             myFormControl1.Invoke(myFormControl1.myDelegate,  
  138.  
  139.                                   new Object[] {myString});  
  140.  
  141.         }  
  142.  
  143.       }  
  144.  
  145.   }  
  146.  

不过这里存在一个有争论的地方:这种方式必须通过调用Control的Invoke方法来实现,这就是说调用的地方必须有一个Control的引用存在。

  看下MyThreadClass类,这个类中就存在MyFormControl的引用对象。其实如果这个类放在这里是没有任务不妥之处的,但是如果把MyThreadClass类放在业务层,这时候问题就出现了,从设计角度来说,业务层是不允许和UI有任何关系,所以MyFormControl的引用对象绝对不能存在于MyThreadClass类,但是不让它存在,更新UI控件的需求就满足不了,这种情况下,我们如何做到一种最佳方案呢!?

第三种方式:

  本文的主角:SynchronizationContext登场了。解释之前,先让下面的代码做下铺垫,

 
  
  1. public partial class Form1 : Form  
  2.  
  3. {  
  4.  
  5.     public Form1()  
  6.  
  7.     {  
  8.  
  9.         InitializeComponent();  
  10.  
  11.     }  
  12.  
  13.  
  14.  
  15.     private void mToolStripButtonThreads_Click(object sender, EventArgs e)  
  16.  
  17.     {  
  18.  
  19.         // let's see the thread id  
  20.  
  21.         int id = Thread.CurrentThread.ManagedThreadId;  
  22.  
  23.         Trace.WriteLine("mToolStripButtonThreads_Click thread: " + id);  
  24.  
  25.  
  26.  
  27.         // grab the sync context associated to this  
  28.  
  29.         // thread (the UI thread), and save it in uiContext  
  30.  
  31.         // note that this context is set by the UI thread  
  32.  
  33.         // during Form creation (outside of your control)  
  34.  
  35.         // also note, that not every thread has a sync context attached to it.  
  36.  
  37.         SynchronizationContext uiContext = SynchronizationContext.Current;  
  38.  
  39.  
  40.  
  41.         // create a thread and associate it to the run method  
  42.  
  43.         Thread thread = new Thread(Run);  
  44.  
  45.  
  46.  
  47.         // start the thread, and pass it the UI context,  
  48.  
  49.         // so this thread will be able to update the UI  
  50.  
  51.         // from within the thread  
  52.  
  53.         thread.Start(uiContext);  
  54.  
  55.     }  
  56.  
  57.  
  58.  
  59.     private void Run(object state)  
  60.  
  61.     {  
  62.  
  63.         // lets see the thread id  
  64.  
  65.         int id = Thread.CurrentThread.ManagedThreadId;  
  66.  
  67.         Trace.WriteLine("Run thread: " + id);  
  68.  
  69.  
  70.  
  71.         // grab the context from the state  
  72.  
  73.         SynchronizationContext uiContext = state as SynchronizationContext;  
  74.  
  75.  
  76.  
  77.         for (int i = 0; i < 1000; i++)  
  78.  
  79.         {  
  80.  
  81.             // normally you would do some code here  
  82.  
  83.             // to grab items from the database. or some long  
  84.  
  85.             // computation  
  86.  
  87.             Thread.Sleep(10);  
  88.  
  89.  
  90.  
  91.             // use the ui context to execute the UpdateUI method,  
  92.  
  93.             // this insure that the UpdateUI method will run on the UI thread.  
  94.  
  95.  
  96.  
  97.             uiContext.Post(UpdateUI, "line " + i.ToString());  
  98.  
  99.         }  
  100.  
  101.     }  
  102.  
  103.  
  104.  
  105.     /// <summary>  
  106.  
  107.     /// This method is executed on the main UI thread.  
  108.  
  109.     /// </summary>  
  110.  
  111.     private void UpdateUI(object state)  
  112.  
  113.     {  
  114.  
  115.         int id = Thread.CurrentThread.ManagedThreadId;  
  116.  
  117.         Trace.WriteLine("UpdateUI thread:" + id);  
  118.  
  119.         string text = state as string;  
  120.  
  121.         mListBox.Items.Add(text);  
  122.  
  123.     }  
  124.  
  125. }  
  126.  

运行结果:

mToolStripButtonThreads_Click thread: 10
Run thread: 3
UpdateUI thread:10
UpdateUI thread:10
UpdateUI thread:10
UpdateUI thread:10
(x1000 times)


    程序首先在Form1窗体的mToolStripButtonThreads_Click事件中,获取当前的SynchronizationContext对象,然后启动另外一个线程,并且将SynchronizationContext对象传递给启动的线程,启动的线程通过SynchronizationContext对象的Post方法来调用一个委托方法UpdateUI,因为UpdateUI是执行在主UI线程上的,所以可以通过它来修改UI上对象的信息。

    怎么样!不错吧,现在我们可以把Control引用给抛弃了,哈哈!

    如果你去查下MSDN,会发现SynchronizationContext还有一个Send方法,Send和Post有什么区别?

Send VS Post,以及异常处理
--------------------------------------------------------------------------------
首先看下异常处理的情况
 
  
  1. private void Run(object state)  
  2.  
  3. {  
  4.  
  5.     // let's see the thread id  
  6.  
  7.     int id = Thread.CurrentThread.ManagedThreadId;  
  8.  
  9.     Trace.WriteLine("Run thread: " + id);  
  10.  
  11.  
  12.  
  13.     // grab the context from the state  
  14.  
  15.     SynchronizationContext uiContext = state as SynchronizationContext;  
  16.  
  17.  
  18.  
  19.     for (int i = 0; i < 1000; i++)  
  20.  
  21.     {  
  22.  
  23.         Trace.WriteLine("Loop " + i.ToString());  
  24.  
  25.         // normally you would do some code here  
  26.  
  27.         // to grab items from the database. or some long  
  28.  
  29.         // computation  
  30.  
  31.         Thread.Sleep(10);  
  32.  
  33.  
  34.  
  35.         // use the ui context to execute the UpdateUI method, this insure that the  
  36.  
  37.         // UpdateUI method will run on the UI thread.  
  38.  
  39.  
  40.  
  41.         try 
  42.  
  43.         {  
  44.  
  45.             uiContext.Send(UpdateUI, "line " + i.ToString());  
  46.  
  47.         }  
  48.  
  49.         catch (Exception e)  
  50.  
  51.         {  
  52.  
  53.             Trace.WriteLine(e.Message);  
  54.  
  55.         }  
  56.  
  57.     }  
  58.  
  59. }  
  60.  
  61.  
  62.  
  63. /// <summary>  
  64.  
  65. /// This method is executed on the main UI thread.  
  66.  
  67. /// </summary>  
  68.  
  69. private void UpdateUI(object state)  
  70.  
  71. {  
  72.  
  73.     throw new Exception("Boom");  
  74.  
  75. }  
  76.  

当你运行的时候, 你可能希望在UI线程上面去抛出,但是结果往往出忽你的意料,异常信息都在Run方法的线程上被捕获了。这时候你可能想问:WHY?!

解释之前,我们先看下,Send VS Post的结果:
Send 方法启动一个同步请求以发送消息
Post 方法启动一个异步请求以发送消息。   

哈哈,异常处理的答案迎韧而解了吧!