borrrden
borrrden

Reputation: 33423

How to emulate Task.Wait() in WinRT?

I have read that if Wait() is called on a Task before it is actually started, then the TaskScheduler may attempt to start the task inline on the thread calling Wait(). This is undesirable to me because I am trying to guarantee the order of execution of some operations, and the inline call may screw that up. Basically, I am exposing two ways to queue items (One async and one sync). The sync method was using Wait() to wait for the result of the operation once it entered the queue on another thread and was executed, but now I have switched it to this:

while(t.Status == TaskStatus.Created)
    Task.Delay(10).Wait();

t.wait();

This looks a bit scary, and smelly, but is there another way to wait for a task to finish without the scheduler attempting to schedule it inline? Waiting like this seems to work, but I'd rather use an alternative method if there is one. I'm restricted to the Windows Runtime Library.

Upvotes: 0

Views: 1378

Answers (2)

svick
svick

Reputation: 245038

If you're trying to guarantee the order of some operations, then you use use the tool that's meant for that: ContinueWith(). If you Wait() on a Task that's returned from that method, you can be sure that the Task won't be started prematurely.

But using Wait() in combination with async methods can be quite dangerous and very often leads to deadlocks. If you have an asynchronous version of a method, there usually shouldn't be any reason for you to create a synchronous version too.

Upvotes: 1

Joachim Isaksson
Joachim Isaksson

Reputation: 181077

@Pako suggested this in the comments, and it seems like a simple enough solution to combine with ContinueWith; this will synchronously wait until MyTask is done;

var manualResetEvent = new ManualResetEvent(false);

Task.Run(() => MyTask()).ContinueWith(x => { manualResetEvent.Set(); });

manualResetEvent.WaitOne();

Upvotes: 2

Related Questions