小编mag*_*gma的帖子

WindowsFormsSynchronizationContext.Current.Post在后台线程上执行lambda

将lambda表达式发布到current时WindowsFormsSynchronizationContext,我发现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);
Run Code Online (Sandbox Code Playgroud)

此外,WindowsFormsSynchronizationContext.Current似乎不返回a WindowsFormsSynchronizationContext,而是一个普通的System.Threading.SynchronizationContext

这突然发生在以前没有线程问题并且最近没有修改过的表单上(解决方案的其他部分)。我曾尝试寻找明显的错误(例如,在后台线程上实例化窗体本身的代码,或在后台线程上创建的控件),但我一直未能找到重大的违规行为。

也许我看错了方向?

c# multithreading winforms

2
推荐指数
1
解决办法
1660
查看次数

标签 统计

c# ×1

multithreading ×1

winforms ×1