Click here to Skip to main content
15,917,177 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'am doing some simple tests with Task.Run in C# 5.0. I have created a Form with a button and label to test it. Should be quite simple, but couldn't get it work so far.

How can i write delayed into the label without blocking the ui ?

Here is my sample code:
private void Button_Click(object sender, EventArgs e)
{
    writeStatus("test 1");
}

private Task taskWriteStatus(string text)
{
    return Task.Run (() =>
    {
        labelWrite(text);
    }); 
}

private void labelWrite(string text)
{
    Task.Delay(300).Wait();
    label1.Text = text;
}

private async void writeStatusAsync (string text)
{
    await taskWriteStatus(text);
}


What I have tried:

I did some research and found differnat approaches to solve this like this good article:
https://blog.imaginea.com/elegant-c-asynchrony/
Posted
Updated 30-May-17 18:02pm
v2

1 solution

Hi, You cannot access UI thread straight away from another thread, UI thread has highest priority. You need to use dispatcher to do it.

just change your labelWrite(string text) method,
C#
private void labelWrite(string text)
{
    Task.Delay(10000).Wait();
    this.Invoke(new MethodInvoker(delegate ()
    {
        label1.Text = text;
    }));
}

And call this method in Button Click. Always try to use dispatcher when you need to update UI from threads.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900