How to asynchronously wait for x seconds and execute something then?

前端 未结 8 854
深忆病人
深忆病人 2020-12-03 03:03

I know there is Thread.Sleep and System.Windows.Forms.Timer and Monitor.Wait in C# and Windows Forms. I just can\'t seem to be able to figure out how to wait fo

相关标签:
8条回答
  • 2020-12-03 03:38

    You are looking at it wrong. Click the button, it kicks off a timer with an interval of x seconds. When those are up it's eventhandler executes the task.

    So what don't you want to happen.

    While the x seconds are elapsing.?

    While The task is executing?

    If for instance it's you don't want the button to be clicked until delay and task are done. Disable it in the button click handler, and enable it on task completion.

    If all you want is a five second delay prior to the task, then you should pass the start delay to the task and let it take care of it.

    0 讨论(0)
  • 2020-12-03 03:45

    You can wait UI thread the way you want it to work.

    Task.Factory.StartNew(async() =>
    {
        await Task.Delay(2000);
    
        // it only works in WPF
        Application.Current.Dispatcher.Invoke(() =>
        {
            // Do something on the UI thread.
        });
    });
    
    0 讨论(0)
提交回复
热议问题