使用异步在一个线程中睡不结冰 [英] Using async to sleep in a thread without freezing

查看:177
本文介绍了使用异步在一个线程中睡不结冰的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我的标签在这里()。当点击该按钮(按钮1),标签文字变为测试。在2秒钟后,文本被设置回,。我做了一个定时器这项工作(其中有2000的区间):

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.

我的code看起来像目前这样:

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

这不,虽然工作。

推荐答案

正如我所提到的code为我工作得很好,但也许尝试设置你的处理程序,以异步,并在那里运行 Task.Delay

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

这篇关于使用异步在一个线程中睡不结冰的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆