线程通讯(SynchronizationContext )

今天看公司其它同事写的代码中用到了SynchronizationContext,看完注释也没明白是什么东东(本人是个入门者,需要充电的地方太多了委屈),所以特别在网上查了下,原来是这么个东西:一个线程和另外一个线程进行通讯时,SynchronizationContext在通讯中充当了个传输者的角色。


先借用下先辈们的例子:

[STAThread]
static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);

    // let's check the context here
    var context = SynchronizationContext.Current;
    if (context == null)
        Console.WriteLine("No context for this thread");
    else
        Console.WriteLine("We got a context");

    // create a form
    Form1 form = new Form1();

    // let's check it again after creating a form
    context = SynchronizationContext.Current;

    if (context == null)
        Console.WriteLine("No context for this thread");
    else
        Console.WriteLine("We got a context");

    if (context == null)
        Console.WriteLine("No context for this thread");

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

如何使用SynchronizationContext

相关链接:

                  http://www.cnblogs.com/Kevin-moon/archive/2009/01/13/1374353.html

                  http://blog.csdn.net/iloli/article/details/16859605







猜你喜欢

转载自blog.csdn.net/w10101010_y/article/details/78612618
今日推荐