WindowsFormsSynchronizationContext.Current.Post在后台线程执行的lambda [英] WindowsFormsSynchronizationContext.Current.Post executes lambda on background thread
问题描述
在发布lambda表达式的电流 WindowsFormsSynchronizationContext
,我发现拉姆达代码执行在后台线程:
When posting a lambda expression to the current WindowsFormsSynchronizationContext
, I find that the lambda code executes on a background thread:
// 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
。
Besides, WindowsFormsSynchronizationContext.Current
does not seem to return a WindowsFormsSynchronizationContext
, but rather an ordinary System.Threading.SynchronizationContext
.
这是突然发生的事情是用于没有螺纹的问题,并没有被最近修改(解决方案的其他部分都)在窗体上。我试图寻找出明显的错误(如在后台线程创建,代码实例化在后台线程的形式本身,或控件),但我一直没能找到显著的违规行为。
This is suddenly happening on a form that used to have no thread problems and hasn't been recently modified (other parts of the solution were). I have tried looking for obvious mistakes (such as, code that instantiates the form itself on a background thread, or controls created on a background thread) but I haven't been able to find significant violations.
也许我期待在错误的方向?
Perhaps I am looking in the wrong direction?
推荐答案
WindowsFormsSynchronizationContext.Current
相同 SynchronizationContext.Current
。你应该让你通过一个派生类中调用基静态成员编译器警告。
WindowsFormsSynchronizationContext.Current
is the same as SynchronizationContext.Current
. You should be getting a compiler warning that you are invoking a base static member through a derived class.
检查 SynchronizationContext.Current.GetType()
,你会发现,你是一个不同的同步上下文中运行。
Check SynchronizationContext.Current.GetType()
and you'll find out that you are running under a different sync context.
夺UI线程上正确的上下文并储存起来。
Capture the correct context on the UI thread and store it.
这篇关于WindowsFormsSynchronizationContext.Current.Post在后台线程执行的lambda的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!