zoukankan      html  css  js  c++  java
  • C#(WPF和WinForm)在普通类中调用到主线程的方法,SynchronizationContext的用法。

    一、SynchronizationContext类用法:

    1、对于WindowsFrom应用程序,如果想在某个类中,不方便使用到控件的Invoke方法时,可以使用WindowsBase.dll下的System.Thread.SynchronizationContext。

    namespace FormDispatcher
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
                Thread.CurrentThread.Name = "这是主线程";
                context = new WindowsFormsSynchronizationContext();
            }
            System.Threading.SynchronizationContext context = null;
            private void button1_Click(object sender, EventArgs e)
            {
                Thread th = new Thread(() =>
                {
                    listBox1.Items.Add(Thread.CurrentThread.Name);
                    context.Send((obj) =>
                    {
                        listBox1.Items.Add(Thread.CurrentThread.Name);
                    }, null);
                });
                th.Name = "这是普通线程";
                th.Start();
            }
        }
    }

    效果:

    2、WPF程序:用法是相同的,只是类不同。

    namespace WpfDispatcher
    {
        /// <summary>
        /// MainWindow.xaml 的交互逻辑
        /// </summary>
        public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();
                dip = System.Windows.Threading.Dispatcher.CurrentDispatcher;
                Thread.CurrentThread.Name = "主线程";
                ds = new System.Windows.Threading.DispatcherSynchronizationContext();
            }
            System.Windows.Threading.Dispatcher dip = null;
            System.Threading.SynchronizationContext ds = null;
            private void Button_Click(object sender, RoutedEventArgs e)
            {
                Thread th = new Thread(() =>
                {
                    dip.Invoke(new Action(() =>
                    {
                        MessageBox.Show(Thread.CurrentThread.Name);//显示主线程
                    }));
    
                    ds.Send((obj) =>
                    {
                        MessageBox.Show(Thread.CurrentThread.Name);//显示主线程
                    }, null);
                });
                th.Start();
            }
        }
    }
  • 相关阅读:
    elasticsearch
    超人学院课课程体系
    51cto大数据培训路线
    关于举办大数据处理技术培训的通知
    “大数据分析高级工程师”培训
    成都大数据Hadoop与Spark技术培训班
    大数据时代新闻采编人员职业能力培训
    EXCEL常用函数
    大数据实时处理-基于Spark的大数据实时处理及应用技术培训
    Properties vs. Attributes
  • 原文地址:https://www.cnblogs.com/songxingzhu/p/5343905.html
Copyright © 2011-2022 走看看