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?
精彩评论