SiberianGuy
SiberianGuy

Reputation: 25282

Execute asynchronous code as synchronous

I have the following asynchronous code:

public async Task<List<PreprocessingTaskResult>> Preprocess(Action onPreprocessingTaskFinished)
{
  var preprocessingTasks = BuildPreprocessingTasks();

  var preprocessingTaskResults = new List<PreprocessingTaskResult>();

  while (preprocessingTasks.Count > 0)
  {
    //Wait till at least one task is completed
     await TaskEx.WhenAny(preprocessingTasks.ToArray());

     onPreprocessingTaskFinished();
  }

  return 
}

And the asynchronous usage code

var preprocessingTaskResults = await Preprocess(someAction);

For some cases I need to call it in synchronous way. For simpler cases (when async method returns just a task) I used to do the following:

var someTask = AsyncMethod();
Task.Wait(someTask);

But I am confused how I should implement it here.

Upvotes: 0

Views: 133

Answers (2)

Stephen Cleary
Stephen Cleary

Reputation: 456322

There is no easy way to call asynchronous code synchronously. Stephen Toub covers some various approaches here but there is no approach that works in all situations.

The best solution is to change the synchronous calling code to be asynchronous. With the advent of Microsoft.Bcl.Async and recent releases of Xamarin, asynchronous code is now supported on .NET 4.0 (and higher), Windows Phone 7.1 (and higher), Windows Store, Silverlight 4 (and higher), iOS/MonoTouch, Android/MonoDroid, and portable class libraries for any mix of those platforms.

So there's very little reason these days not to use async.

But if you absolutely need a synchronous API, then the best solution is to make it synchronous all the way. If you do need both asynchronous and synchronous APIs, this will cause code duplication which is unfortunate but it is the best solution at this time.

Upvotes: 1

dcastro
dcastro

Reputation: 68640

A task's Result property will block until the task completes and then return its result:

List<PreprocessingTaskResult> result = Preprocess(someAction).Result;

http://msdn.microsoft.com/en-us/library/dd321468(v=vs.110).aspx

Upvotes: 3

Related Questions