简体   繁体   English

Windows Store中.NET中的Thread.Sleep替换

[英]Thread.Sleep replacement in .NET for Windows Store

Thread.Sleep doesn't seem to be supported in .NET for Windows Store apps. Windows Store应用程序的.NET中似乎不支持Thread.Sleep

For example, this 例如这个

System.Threading.Thread.Sleep(1000);

will compile when targeting any .NET Framework (2.0, 3.5, 4.0, 4.5), but not when targeting .NET for Windows Store apps (or in a portable class library which targets both 4.5 and store). 面向任何.NET Framework(2.0、3.5、4.0、4.5)时将编译,而针对Windows Store应用程序(或面向4.5和商店的可移植类库)面向.NET时将不会编译。

System.Threading.Thread is still there, it just doesn't have the Sleep method. System.Threading.Thread仍然存在,只是没有Sleep方法。

I need to delay something for a few seconds in my app, is there a suitable replacement? 我需要在应用程序中延迟几秒钟,是否有合适的替代品?

EDIT why the delay is needed: My app is a game and the delay is to make it look like the computer opponent is "thinking" about his next move. 编辑为什么需要延迟:我的应用是游戏,延迟是使它看起来像计算机对手在“思考”他的下一步行动。 The method is already called asynchronously (main thread isn't blocked), I just want to slow the response time down. 该方法已经被异步调用(没有阻塞主线程),我只想减慢响应时间。

Windows Store apps embrace asynchrony - and an "asynchronous pause" is provided by Task.Delay . Windows应用商店应用程序具有异步性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. 异步方法将在30秒后继续,但是不会像所有await表达式一样阻塞线程。

讨厌表述明显,但万一有人要一行System.Threading.Tasks.Task.Delay(3000).Wait()

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): 如果您真的想阻塞线程,我会这样做(感谢@Brannon提供“苗条”的提示):

// `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));
}

MainPage.xaml.cs 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!
}

There is almost NO reason (except for testing purposes) to EVER use Thread.Sleep() . 几乎没有理由(出于测试目的)永远不要使用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. 如果(且仅当)您有充分的理由将线程发送到睡眠状态,则可能要检查Task.Delay() ,您可以在指定的时间内等待“等待”。 Though it's never a good idea to have a thread sitting around and do nothing. 虽然让线程无所事事绝不是一个好主意。 Bad practise ... 坏习惯...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM