等待几秒钟而不会阻止UI执行

编程入门 行业动态 更新时间:2024-10-28 16:16:53
本文介绍了等待几秒钟而不会阻止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执行

本文发布于:2023-06-07 22:45:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/572845.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:几秒钟   UI

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!