Thread.Sleep replacement in .NET for Windows Store

后端 未结 5 2029
逝去的感伤
逝去的感伤 2020-11-30 21:34

Thread.Sleep doesn\'t seem to be supported in .NET for Windows Store apps.

For example, this

System.Threading.Thread.Sleep(1000);

相关标签:
5条回答
  • 2020-11-30 22:06

    There is almost NO reason (except for testing purposes) to EVER use Thread.Sleep().

    IF (and only if) you have a very good reason to send a thread to sleep, you might want to check Task.Delay() , which you can await to "wait" for a specified time. Though it's never a good idea to have a thread sitting around and do nothing. Bad practise ...

    0 讨论(0)
  • 2020-11-30 22:12

    MainPage.xaml.cs

    public MainPage()
    {
      this.InitializeComponent();
      this.WaitForFiveSeconds();
    }
    
    private async void WaitForFiveSeconds()
    {
      await System.Threading.Tasks.Task.Delay(TimeSpan.FromSeconds(5));
      // do something after 5 seconds!
    }
    
    0 讨论(0)
  • 2020-11-30 22:25

    Windows Store apps embrace asynchrony - and an "asynchronous pause" is provided by Task.Delay. So within an asynchronous method, you'd write:

    await Task.Delay(TimeSpan.FromSeconds(30));
    

    ... or whatever delay you want. The asynchronous method will continue 30 seconds later, but the thread will not be blocked, just as for all await expressions.

    0 讨论(0)
  • 2020-11-30 22:27

    Hate to state the obvious but in case anybody wanted a single line System.Threading.Tasks.Task.Delay(3000).Wait()

    0 讨论(0)
  • 2020-11-30 22:29

    I just had the same problem and found another interesting solution that I wanted to share with you. If you really want to block the thread I would do it like this (thanks @Brannon for the "slim" hint):

    // `waitHandle.Set` is never called, so we wait always until the timeout occurs
    using (var waitHandle = new ManualResetEventSlim(initialState: false))
    {
        waitHandle.Wait(TimeSpan.FromSeconds(5));
    }
    
    0 讨论(0)
提交回复
热议问题