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();
        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM