Wait for n seconds, then next line of code without

2019-02-06 04:02发布

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.

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.

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 :(

4条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-02-06 04:36

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);
}
查看更多
甜甜的少女心
3楼-- · 2019-02-06 04:51
DateTime Tthen = DateTime.Now;
            do
            {
                Application.DoEvents();
            } while (Tthen.AddSeconds(5) > DateTime.Now);    
查看更多
趁早两清
4楼-- · 2019-02-06 05:02

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

public async Task Foo()
{
    await Task.Delay(2000);
    txtConsole.AppendText("Waiting...");
    DoStuff();
}
查看更多
我命由我不由天
5楼-- · 2019-02-06 05:02

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!";
}
查看更多
登录 后发表回答