一、SynchronizationContext顾名思义是同步上下文的意思。利用此对象可以实现线程间数据的同步、异步访问。
二、例子
class Program { static Thread _workThread; static SynchronizationContext _mainThreadSynContext; static void Main(string[] args) { _mainThreadSynContext = SynchronizationContext.Current; if (_mainThreadSynContext == null) { _mainThreadSynContext = new SynchronizationContext(); } _workThread = new Thread(new ThreadStart(DoWork)); _workThread.Start(); Console.ReadLine(); } static void DoWork() { int a = 10; _mainThreadSynContext.Post(new SendOrPostCallback(ThreadCallBack),a); } static void ThreadCallBack(object state) { Console.WriteLine((int)state); Console.ReadLine(); } }
三、需要特别注意的是
SynchronizationContext.Current可能获取到的是空
此时应该:
if (_mainThreadSynContext == null) { _mainThreadSynContext = new SynchronizationContext(); }