Kyaw Nyi Win
Kyaw Nyi Win

Reputation: 81

Why Task Parallel Library can update UI simply?

When I try update UI using Task in .net Framework 4, I found out that something strange. I never thought UI thread can be updated from Task Library. I just wanted to test it and amazingly it works. Here is my code, can someone explain how it works ?

public Form1()
{
    InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
    int i=0;
    Task myTask = new Task(() =>
    { 
        while (true) 
        { 
            label1.Text = "Hello" + i++; 
            Thread.Sleep(3000); 
        }; 
    });

    myTask.Start();
}

Upvotes: 0

Views: 106

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039298

The fact that you didn't get an exception this time doesn't mean that you (or even worse your customer) won't get an exception the next time. You were just lucky. Make sure you marshal all function calls to the UI on the main thread. Or if you want to spare this task use a BackgroundWorker which will take care of executing the callback on the main thread.

Upvotes: 3

Related Questions