在发布lambda表达式到当前WindowsFormsSynchronizationContext
,我发现拉姆达代码执行在后台线程:WindowsFormsSynchronizationContext.Current.Post后台线程执行拉姆达
// 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从另一个线程查询时,你必须将其保存以备后用 –
不是null;投射时它是空的。我会澄清,谢谢@Sriram。 – magma
这将是空的,请澄清 –