72

So I a label here (""). When the button (button1) is clicked, the label text turns into "Test". After 2 seconds, the text is set back into "". I made this work with a timer (which has an interval of 2000):

private void button1_Click(object sender, EventArgs e)
{
    label1.Text = "Test";
    timer.Enabled = true;
}

private void timer_Tick(object sender, EventArgs e)
{
    label1.Text = "";
}

This works; however though, I am curious about making it work in an async method.

My code looks like this currently:

private void button1_Click(object sender, EventArgs e)
{
    label1.Text = "Test";
    MyAsyncMethod();
}

public async Task MyAsyncMethod()
{
    await Task.Delay(2000);
    label1.Text = "";
}

This doesn't work though.

jacobz
  • 3,191
  • 12
  • 37
  • 61
  • I just tried your method and it works fine, on click it changes to "Test" 2 seconds later it changes to "" – sa_ddam213 Jun 02 '13 at 00:01
  • 1
    Could you expound on "This doesn't work"? What were you expecting and what did you observe? Compiler errors? Exception stack traces? – Stephen Cleary Jun 02 '13 at 00:55

1 Answers1

144

As I mentioned your code worked fine for me, But perhaps try setting your handler to async and running the Task.Delay in there.

private async void Button_Click_1(object sender, RoutedEventArgs e)
{
    label1.Text = "Test";
    await Task.Delay(2000);
    label1.Text = "";
}
sa_ddam213
  • 42,848
  • 7
  • 101
  • 110
  • 2
    Yeah, I think it was really difficult to tell what my problem was. However though, this seems to work without any problems :) Thank you and I'll try to word future questions more careful. – jacobz Jun 02 '13 at 17:26
  • 3
    For those who do not wish to create an async function: `Task.Delay(2000).Wait();` – Josh Mc Dec 30 '16 at 01:57
  • 5
    @JoshMc You are right, but that would cause the GUI thread to be blocked for 2 seconds. That's not a good solution. – sighol Jan 17 '17 at 10:01
  • True - only recently realized this, good point .Wait() is not preferable, for the vast majority of circumstances. – Josh Mc Jan 18 '17 at 03:33