Using async to sleep in a thread without freezing [closed]

大兔子大兔子 提交于 2019-12-18 13:52:45

问题


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.


回答1:


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 = "";
}


来源:https://stackoverflow.com/questions/16878434/using-async-to-sleep-in-a-thread-without-freezing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!