簡體   English   中英

為什么System.Windows.Forms BeginInvoke在WPF中似乎可以工作

[英]Why does System.Windows.Forms BeginInvoke seem to work in WPF

我是WPF的新手。 在嘗試使用WPF及其線程模型時,我嘗試進行一些試驗。

我在MainWindow.xaml.cs中運行了以下代碼行。

    var sync = SynchronizationContext.Current;

//返回System.Windows.Threading.DispatcherSynchronizationContext //

    var frm = new System.Windows.Form();
    IntPtr temp = frm.Handle;
    sync = SynchronizationContext.Current;

//仍然同步的是System.Windows.Threading.DispatcherSynchronizationContext。 所以我有點猜測,如果SynchronizationContext.Current為null,則System.Windows.Form將創建System.Windows.Forms.WindowsFormsSynchronizationContext。

//現在出現了奇怪的部分。

    Thread th = new Thread(() =>
                           {
                                     Action strac = UpdateTextBox;
                                     frm.BeginInvoke(strac);
                           });
    th.Start();



    void UpdateTextBox()
    {
        textBox1.Text = "Abhik";
    }

//我試圖使用System.Windows.Form的BeginInvoke將請求編組回UI線程,並更新了UI控件。

有效!!..

能否請任何人告訴我它為什么起作用。 這是因為WPF控件和winform控件在Windows操作系統中共享相同的祖先,即User32.dll和DispatcherSynchronizationContext和WindowsFormsSynchronizationContext在內部執行相同的操作。

任何幫助將不勝感激。

您是正確的,只有在當前AsyncOperationManager.SynchronizationContextnull或基SynchronizationContext類的實例的情況下,才創建WindowsFormsSynchronizationContext

BeginInvokeInvoke方法不使用SynchronizationContext 相反,他們走在控件的祖先上,找到具有有效窗口句柄的第一個控件,將委托添加到私有隊列中,並將私有消息發布到窗口中。 WndProc例程在正確的線程上接收此消息,並調用排隊的委托。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM