等待n秒,然后下一行代码不冻结表单 [英] Wait for n seconds, then next line of code without freezing form

查看:18
本文介绍了等待n秒,然后下一行代码不冻结表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找到一种在移动到下一行代码之前等待数毫秒的方法,

Hi I am trying to find a method of waiting a number of milliseconds before moving to the next line of code,

我已经研究了 Thread.Sleep 但这会冻结主窗体,我希望它保持活动状态.

I have looked into Thread.Sleep but this will freeze the main form, I would like this to remain active.

我尝试了计时器和秒表,当它们打勾时应该发布到控制台时,它们都会冻结主表单.

I tried timers and stopwatches and both freeze the main form when they should be posting to a console when they tick.

我也找不到在我想要的等待中使用 task.delay 或后台工作程序的方法.

I couldn't find a way of using task.delay or background worker in the wait I wanted either.

伪代码:

Wait 2 - 6 seconds
Log "waiting"
Log "waiting"
Log "waiting"
Stop Waiting - Run next line of code.

我尝试过的方法只是冻结表单并在之后填写日志,我只想要一个简单的方法来等待而不冻结表单并且不必处理被调用的事件,这意味着下一行没有运行.

The methods I have tried just freeze up the form and fill the log afterwards, I just want a simple method of waiting without freezing the form and without having to deal with events being called which would mean the next line isn't run.

任何帮助都会很棒,因为我还是 C# 的新手,这让我有点生气:(

Any help would be awesome because I am still new to c# and its been driving me a bit mad :(

推荐答案

await 关键字与 Task.Delay 结合使用使这变得微不足道.

The await keyword, in conjunction with Task.Delay makes this trivial.

public async Task Foo()
{
    await Task.Delay(2000);
    txtConsole.AppendText("Waiting...");
    DoStuff();
}

这篇关于等待n秒,然后下一行代码不冻结表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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