奇妙的SynchronizationContext2011-11-14 博客园 Kevin-moon上一篇中已经讲了SynchronizationContext 的一些内容,现在让我们更加深入地去了解它!继上篇中的问题"在UI线程上对SynchronizationContext的使用,可以适用于其他线程呢?"OK,我们把它放置在非UI线程上,这是你用SynchronizationContext.Current的属性来获取,你会发 现你得到的是null,这时候,你可能会说,既然它不存在,那么我自己创建一个SynchronizationContext 对象,这样就没问题了吧!?可是,最后它并不会像UI线程中那样去工作。让我们看下面的例子:
class Program{private static SynchronizationContext mT1 = null;static void Main(string[] args){// log the thread idint id = Thread.CurrentThread.ManagedThreadId;Console.WriteLine("Main thread is " + id);// create a sync context for this threadvar context = new SynchronizationContext();// set this context for this thread.SynchronizationContext.SetSynchronizationContext(context);// create a thread, and pass it the main sync context.Thread t1 = new Thread(new ParameterizedThreadStart(Run1));t1.Start(SynchronizationContext.Current);Console.ReadLine();}static private void Run1(object state){int id = Thread.CurrentThread.ManagedThreadId;Console.WriteLine("Run1 Thread ID: " + id);// grabthe sync context that main has setvar context = state as SynchronizationContext;// call the sync context of main, expecting// the following code to run on the main thread// but it will not.context.Send(DoWork, null);while (true)Thread.Sleep(10000000);}static void DoWork(object state){int id = Thread.CurrentThread.ManagedThreadId;Console.WriteLine("DoWork Thread ID:" + id);}}