上一篇中已经讲了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 id int id = Thread.CurrentThread.ManagedThreadId; Console.WriteLine("Main thread is " + id); // create a sync context for this thread var 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); // grab the sync context that main has set var 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); } }
以上是小编为您精心准备的的内容,在的博客、问答、公众号、人物、课程等栏目也有的相关内容,欢迎继续使用右上角搜索按钮进行搜索线程
, static
, thread
, context
console
synchronization、undo synchronization、no synchronization、beam synchronization、synchronization 缩写,以便于您获取更多的相关知识。
时间: 2024-11-02 02:46:26