C# 为什么System.Windows.Forms BeginInvoke似乎在WPF中工作
我是WPF的新手。在试验WPF及其线程模型时,我尝试做了一些试验 我在主窗口.xaml.cs中运行了以下代码行C# 为什么System.Windows.Forms BeginInvoke似乎在WPF中工作,c#,C#,我是WPF的新手。在试验WPF及其线程模型时,我尝试做了一些试验 我在主窗口.xaml.cs中运行了以下代码行 var sync = SynchronizationContext.Current; //返回System.Windows.Threading.DispatcherSynchronizationContext// var frm = new System.Windows.Form(); IntPtr temp = frm.Handle; sync =
var sync = SynchronizationContext.Current;
//返回System.Windows.Threading.DispatcherSynchronizationContext//
var frm = new System.Windows.Form();
IntPtr temp = frm.Handle;
sync = SynchronizationContext.Current;
//仍然是System.Windows.Threading.DispatchersSynchronizationContext。所以我猜如果SynchronizationContext.Current为空,System.Windows.Forms.WindowsFormsSynchronizationContext会创建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操作系统ie User32.dll和DispatcherSynchronizationContext中具有相同的祖先,而WindowsFormsSynchronizationContext在内部执行相同的操作
任何帮助都将不胜感激。如果当前的
AsyncOperationManager.SynchronizationContext
为null
或基本SynchronizationContext
类的实例,则创建WindowsFormsSynchronizationContext
是正确的
BeginInvoke
和Invoke
方法不使用SynchronizationContext
。相反,它们遍历控件的祖先以找到第一个具有有效窗口句柄的控件,将委托添加到私有队列,并向窗口发布私有消息。WndProc
例程在正确的线程上接收此消息,并调用排队的委托