0

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.

1
  • 1
    The best solution would be actually not create tasks at all and return just some delegate and call it directly, this can be done in BuildPreprocessingTasks Commented Nov 15, 2013 at 11:21

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

The problem with this is that it often causes deadlocks.
Only if you're on an environment that uses a synchronization context. If it does cause a deadlock, read this: blog.stephencleary.com/2012/07/dont-block-on-async-code.html
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.