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

橙三吉。 提交于 2019-11-29 01:24:17

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

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

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

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.

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

void async MyMethod()
{  
    var result = await Task.Run(() => long_running_code);
}
DateTime Tthen = DateTime.Now;
            do
            {
                Application.DoEvents();
            } while (Tthen.AddSeconds(5) > DateTime.Now);    
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!