C# 等待n秒,然后下一行代码不冻结表单

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16003090/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 23:19:45  来源:igfitidea点击:

Wait for n seconds, then next line of code without freezing form

c#timerdelaywait

提问by Sam

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

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

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

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

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

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

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

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

Pseudo Code:

伪代码:

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.

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

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

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

采纳答案by Servy

The awaitkeyword, in conjunction with Task.Delaymakes this trivial.

await关键字,会同Task.Delay使这个微不足道的。

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

回答by Daniel

Try using a DispatcherTimer. It's a pretty handy object that does all the work of delegating to the UI thread.

尝试使用DispatcherTimer。这是一个非常方便的对象,可以完成委托给 UI 线程的所有工作。

For example:

例如:

private DispatcherTimer _dtTimer = null;

public Constructor1(){
  _dtTimer = new DispatcherTimer();
  _dtTimer.Tick += new System.EventHandler(HandleTick);
  _dtTimer.Interval = new TimeSpan(0, 0, 0, 2); //Timespan of 2 seconds
  _dtTimer.Start();
}

private void HandleTick(object sender, System.EventArgs e) {
  _uiTextBlock.Text = "Timer ticked!";
}

回答by alex

Timer should work fine in this case, unless you put Thread.Sleep in its handler or the handler itself takes too much time to complete.

在这种情况下,计时器应该可以正常工作,除非您将 Thread.Sleep 放在其处理程序中或处理程序本身需要太多时间才能完成。

You haven't specified the UI framework that you use or .Net version, but for the latest .Net you can use async/await. That way, UI would not be frozen while your code awaits for the background task

您尚未指定您使用的 UI 框架或 .Net 版本,但对于最新的 .Net,您可以使用 async/await。这样,当您的代码等待后台任务时,UI 不会被冻结

void async MyMethod()
{  
    var result = await Task.Run(() => long_running_code);
}

回答by Ahmad Hamdeen

DateTime Tthen = DateTime.Now;
            do
            {
                Application.DoEvents();
            } while (Tthen.AddSeconds(5) > DateTime.Now);