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

查看:24
本文介绍了等待几秒钟而不阻止 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天全站免登陆