等待几秒钟而不会阻止UI执行 [英] Wait some seconds without blocking UI execution

查看:56
本文介绍了等待几秒钟而不会阻止UI执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在两条指令之间等待几秒钟,但不会阻塞执行。

I would like to wait some seconds between two instruction, but WITHOUT blocking the execution.

例如, Thread.Sleep(2000) 不好,因为它会阻止执行。

For example, Thread.Sleep(2000) it is not good, because it blocks execution.

这个想法是我先调用一个方法,然后等待X秒(例如20 )收听即将到来的事件。在20秒结束时,我应该根据20秒中发生的事情进行一些操作。

The idea is that I call a method and then I wait X seconds (20 for example) listening for an event coming. At the end of the 20 seconds I should do some operation depending on what happened in the 20 seconds.

推荐答案

我认为您在做什么之后是Task.Delay。这不会像Sleep那样阻塞线程,这意味着您可以使用异步编程模型在单个线程中执行此操作。

I think what you are after is Task.Delay. This doesn't block the thread like Sleep does and it means you can do this using a single thread using the async programming model.

async Task PutTaskDelay()
{
    await Task.Delay(5000);
} 

private async void btnTaskDelay_Click(object sender, EventArgs e)
{
    await PutTaskDelay();
    MessageBox.Show("I am back");
}

这篇关于等待几秒钟而不会阻止UI执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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