Thread.Sleep (asynchronously) in a Windows Store App (WinRT)

UPDATE:  Another option is to use await Task.Delay(ms) which would require you to be in an async method (which my examples are).

I thought I had a simple idea that would require simple code: In my “service mock” class I wanted to sleep the thread for 2 seconds to simulate a real web service call to see how my UI reacted.

Simple, right? Just throw a good-ol’ Thread.Sleep() in there and all is well? Nope!

Issue #1 – System.Threading.Thread is no more …
Luckily, a quick Internet search (I refuse to turn the name of my search engine into a verb) revealed a “hack” to sleep on a thread:

new System.Threading.ManualResetEvent(false).WaitOne(ms);

Issue#2 – But it blocks my thread.
Ok … but this blocks my thread and C# 5 gives me a nice async/await pattern so as not to block my thread and MRE is not awaitable.  Ok … I’ll just spawn off a task and sleep on it.

await Task.Run(() => { new System.Threading.ManualResetEvent(false).WaitOne(2000); });

Or use Task.Delay inside an async lamba or method:

await Task.Delay(2000);

There you have it.  I can now simulate a slow web service call in my stub/mock service implemenation.

Post a comment if there is a better way to do it or just to contemplate the deep meaning of  “Sleep asynchronously.”

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s