zoukankan      html  css  js  c++  java
  • 同步上下文 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);
    }



  • 相关阅读:
    Java 创建过滤器 解析xml文件
    web页面隐藏鼠标
    dom4j微信接口开发
    php实现远程网络文件下载到服务器指定目录 阿星小栈
    laravel 框架给$request添加数据 阿星小栈
    Agreeing to the Xcode/iOS license requires admin privileges, please run “sudo xcodebuild -license” and then retry this command. 阿星小栈
    在vue项目中使用echarts 阿星小栈
    js 数组、时间、邮箱等处理方法 阿星小栈
    iview 在Table组件render 中使用Poptip组件 阿星小栈
    逐步解决动态添加样式导致的元素闪烁 阿星小栈
  • 原文地址:https://www.cnblogs.com/kiminozo/p/2340609.html
Copyright © 2011-2022 走看看