2013-02-13 36 views
0

我對WPF很陌生。在嘗試使用WPF及其線程模型時,我試圖做一些實驗。爲什麼System.Windows.Forms BeginInvoke似乎在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。所以我有點猜測System.Windows.Form創建System.Windows.Forms.WindowsFormsSynchronizationContext,如果SynchronizationContext.Current爲null。//

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

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在內部執行相同的操作。

任何幫助將不勝感激。

回答

0

如果當前AsyncOperationManager.SynchronizationContextnull或基類SynchronizationContext類的實例,則僅當WindowsFormsSynchronizationContext被創建時,纔是正確的。

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

相關問題