开发者

Why is a non UI thread able to modify UI control in WinForm & TPL?

I was testing a piece of TPL code I wrote below. The two ManagedThreadId's display different numbers. The new task therefore, I am assuming, is running on a non UI thread.

My question is how is the task able to display a message and change a UI control? I am missing something. I thought I needed to get a reference to the UI's SynchronizationContext and use it to make UI changes from other threads.

//var uiScheduler = 开发者_StackOverflowTaskScheduler.FromCurrentSynchronizationContext();
MessageBox.Show(Thread.CurrentThread.ManagedThreadId.ToString());

Task testTask = new Task(() => {
        MessageBox.Show(
            Thread.CurrentThread.ManagedThreadId.ToString());
        lblTest.Text = "Test";
    });
testTask.Start();

Addition:

Download VS solution here

Addition 2

Can someone test the solution and mention if they get an exception or not?


This will not work unless you use the Control.CheckForIllegalCrossThreadCalls property to instruct the runtime not to validate that the calling thread matches the thread that the control was created on.

Your test code does crash for me in a brand new WinForms project (InvalidOperationException: Cross-thread operation not valid: Control 'lblTest' accessed from a thread other than the thread it was created on). Is it possible that CheckForIllegalCrossThreadCalls(false) is being applied in your environment?

Why is a non UI thread able to modify UI control in WinForm & TPL?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜