• 同步上下文 SynchronizationContext 学习笔记


    提供在各种同步模型中传播同步上下文的基本功能。,同步上下文的工作就是确保调用在正确的线程上执行。

    同步上下文的基本操作

    Current 获取当前同步上下文

    var context = SynchronizationContext.Current;
    
    

    Send 一个同步消息调度到一个同步上下文。

    SendOrPostCallback callback = o =>
    {
    //TODO:
    };
    context.Send(callback,null);

    send调用后会阻塞直到调用完成。

    Post 将异步消息调度到一个同步上下文。

    SendOrPostCallback callback = o =>
    {
    //TODO:
    };
    context.Post(callback,null);

    和send的调用方法一样,不过Post会启动一个线程来调用,不会阻塞当前线程。

    使用同步上下文来更新UI内容

    无论WinFroms和WPF都只能用UI线程来更新界面的内容

    常用的调用UI更新方法是Inovke(WinFroms):

    private void button_Click(object sender, EventArgs e)
    {
    ThreadPool.QueueUserWorkItem(BackgroudRun);
    }

    private void BackgroudRun2(object state)
    {
    this.Invoke(new Action(() =>
    {
    label1.Text = "Hello Invoke";
    }));
    }

    使用同步上下文也可以实现相同的效果,

    WinFroms和WPF继承了SynchronizationContext,使同步上下文能够在UI线程或者Dispatcher线程上正确执行

    System.Windows.Forms. WindowsFormsSynchronizationContext
    System.Windows.Threading. DispatcherSynchronizationContext

    调用方法如下:

    private void button_Click(object sender, EventArgs e)
    {
    var context = SynchronizationContext.Current; //获取同步上下文
    Debug.Assert(context != null);
    ThreadPool.QueueUserWorkItem(BackgroudRun, context);
    }


    private void BackgroudRun(object state)
    {
    var context = state as SynchronizationContext; //传入的同步上下文
    Debug.Assert(context != null);
    SendOrPostCallback callback = o =>
    {
    label1.Text = "Hello SynchronizationContext";
    };
    context.Send(callback,null); //调用
    }



    使用.net4.0的Task 可以简化成

    private void button_Click(object sender, EventArgs e)
    {
    var scheduler = TaskScheduler.FromCurrentSynchronizationContext(); // 创建一个SynchronizationContext 关联的 TaskScheduler
    Task.Factory.StartNew(() => label1.Text = "Hello TaskScheduler", CancellationToken.None,
    TaskCreationOptions.None, scheduler);
    }



  • 相关阅读:
    easyui datetimebox 日期控件绑定双击日期选择时间
    js 中call和apply的应用
    js中数组的合并和对象的合并
    flex也可以让背景透明
    收集了一些as的面试题,给HR准备的
    [转]PureMVC的十个小提示
    12个Flex常用功能代码
    43个热门Flex和ActionScript 3.0 APIs,技巧和工具[转]
    转载+原创PureMVC 实例讲解
    PureMVC使用时的注意事项
  • 原文地址:https://www.cnblogs.com/kiminozo/p/2340609.html
Copyright © 2020-2023  润新知