[英]Wait for n seconds, then next line of code without freezing form
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#的新手,这让我有点生气:(
The await
keyword, in conjunction with Task.Delay
makes this trivial. 将
await
关键字与Task.Delay
结合使用Task.Delay
简单。
public async Task Foo()
{
await Task.Delay(2000);
txtConsole.AppendText("Waiting...");
DoStuff();
}
Try using a DispatcherTimer . 尝试使用DispatcherTimer 。 It's a pretty handy object that does all the work of delegating to the UI thread.
这是一个非常方便的对象,它完成了委派给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!";
}
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. 您尚未指定要使用的UI框架或.Net版本,但对于最新的.Net,可以使用async / await。 That way, UI would not be frozen while your code awaits for the background task
这样,在您的代码等待后台任务时不会冻结UI
void async MyMethod()
{
var result = await Task.Run(() => long_running_code);
}
DateTime Tthen = DateTime.Now;
do
{
Application.DoEvents();
} while (Tthen.AddSeconds(5) > DateTime.Now);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.