【发布时间】:2013-07-16 13:18:08
【问题描述】:
在向当前WindowsFormsSynchronizationContext 发布 lambda 表达式时,我发现 lambda 代码在后台线程上执行:
// running on main thread here
myLabel = new Label();
this.Controls.Add(myLabel);
WindowsFormsSynchronizationContext.Current.Post( ignore => {
// returns true !
bool invokeRequired = myLabel.InvokeRequired;
// returns a background thread, not the UI thread
int threadId = System.Threading.Thread.CurrentThread.ManagedThreadId;
// throws, because we are (unexpectedly) on a background, different thread
myLabel.Text = "whatever";
},null);
此外,WindowsFormsSynchronizationContext.Current 似乎返回的不是WindowsFormsSynchronizationContext,而是一个普通的System.Threading.SynchronizationContext。
这突然发生在一个过去没有线程问题并且最近没有修改过的表单上(解决方案的其他部分是)。我尝试寻找明显的错误(例如,在后台线程上实例化表单本身的代码,或在后台线程上创建的控件),但我无法找到明显的违规行为。
也许我看错了方向?
【问题讨论】:
-
WindowsFormsSynchronizationContext.Current从另一个线程查询时会返回 null,您必须保存以备后用 -
不为空;施法时为空。我会澄清的,谢谢@Sriram。
-
它将为空,请澄清
-
@SriramSakthivel 很清楚:提供给
Post的委托实际上被调用了,因此有一个SynchronizationContext。问题是从该委托访问 UI 失败,因为它没有在 UI 线程上运行。 -
@magma
SynchronizationContext.Current.GetType()在调试器中为您提供什么?
标签: c# multithreading winforms