Reputation: 81
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
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