Tony_Henrich
Tony_Henrich

Reputation: 44195

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 = TaskScheduler.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?

Upvotes: 2

Views: 301

Answers (1)

Eric J.
Eric J.

Reputation: 150148

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?

Getting exception with your source code

Upvotes: 3

Related Questions