首页 > 代码库 > SynchronizationContext的研究之一(非WPF及Forms)

SynchronizationContext的研究之一(非WPF及Forms)

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading;
 6 
 7 
 8 namespace SynchronizationTest003
 9 {
10     class Program
11     {
12         static void Main(string[] args)
13         {
14             SynchronizationContext sc = new SynchronizationContext();
15             Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
16             testA(sc);
17 
18             Console.ReadKey();
19         }
20 
21         public static void testA(object state)
22         {
23             SynchronizationContext sc = state as SynchronizationContext;
24             Console.WriteLine("Start");
25             Console.WriteLine("Func A‘s ManagedThreadID is: " + Thread.CurrentThread.ManagedThreadId);
26             sc.Post(testB,state);
27             Console.WriteLine("End");
28         }
29 
30         public static void testB(object state)
31         {
32             Console.WriteLine("Func B‘s ManagedThreadID is: " + Thread.CurrentThread.ManagedThreadId);
33             Thread.Sleep(3000);
34             SynchronizationContext sc = state as SynchronizationContext;
35             sc.Post(testC,null);
36         }
37 
38         public static void testC(object state)
39         {
40             Console.WriteLine("Func C‘s ManagedThreadID is: " + Thread.CurrentThread.ManagedThreadId);
41             Thread.Sleep(3000);
42             SynchronizationContext sc = state as SynchronizationContext;
43         }
44     }
45 }

运行结果: