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();
        }
    }
}
原文地址:https://www.cnblogs.com/songxingzhu/p/5343905.html