How to create a task from already asynchronous code?

I have code that is already asynchronous - just not using the Task system. I would like to make this an easy task, if possible, so that the code can use it as a task.

So, I want to accept this:

void BeginThing(Action callback);

And turn it into this pseudo code:

Task MyBeginThing() {
   Task retval = // what do I do here?
   BeginThing(() => retval.Done())
   return retval;
}

Is it possible? I do not want to use a mutex and another thread as a solution.

+4
source share
1 answer

Use TaskCompletionSource:

Task MyBeginThing() {
   var taskSource = new TaskCompletionSource<object>();
   BeginThing(() => taskSource.SetResult(null));
   return taskSource.Task;
}

It is also quite common to adapt APIs that use events to signal asynchronous completion. If this is an old school asynchronous Begin / End async pair (for example, an asynchronous programming model or APM), is TaskFactory.FromAsyncalso useful.

+14

All Articles