C# 多线程学习 十一:同步上下文

本文介绍了如何在WPF应用程序中利用SynchronizationContext类进行线程间通信,特别是子线程向UI主线程发送数据的方法。通过设置静态属性SynchronizationContext.Current并在子线程中调用Post方法,可以安全地更新UI元素,类似于Dispatcher的BeginInvoke方法。示例代码展示了如何在后台线程中更新WPF文本框的内容。
摘要由CSDN通过智能技术生成
  1. 在system.componentModel 下有一个抽象类: SynchronizationContext 他使得Thread Marshaling得到泛型化。
  2. 针对移动 桌面 等富客户端应用api 他们都定义和实例化了synchronzzationContext的子类
  3. 可以通过静态属性Synchronizationcontext.Current 来获取(当运行在UI线程是)
  4. 捕获改属性后你可以供任何子线程通过Post方法想UI主线程发送数据。
  5. 调用Post就相当于调用Dispath 或Control 上面的BeginInvoke 方法。还有一个send方法相当于BeginInvoke

for text WPF code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Threading;

namespace WPFMgs
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private static SynchronizationContext UIContext;
        public MainWindow()
        {
            InitializeComponent();
            UIContext = SynchronizationContext.Current;
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            new Thread(Work).Start();
        }

        void Work()
        {
            Thread.Sleep(5000);
            //this.textBlock1.Text = "Wpftextbox";
            UpDataMgs("Wpftextbox");
        }
        void UpDataMgs(string str)
        {
           //Action action =()=>{textBlock1.Text=str;};
           //Dispatcher.BeginInvoke(action);
            UIContext.Post(_ => { textBlock1.Text = str; },null);
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

望天hous

你的鼓励是我最大动力~谢谢啦!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值