4

I have some code that's already asynchronous - just not using the Task system. I would like to make it a lightweight Task, if possible, so that code may leverage it as a Task.

So I want to take this:

void BeginThing(Action callback);

And turn it into this pseudocode:

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

Is this possible? I don't want to use a mutex and another thread as a solution.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
xtravar
  • 1,321
  • 11
  • 24

1 Answers1

14

Use TaskCompletionSource:

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

This is also fairly common for adapting APIs that use events to signal asynchronous completion. If it is an old school Begin/End async pair (aka the Asynchronous Programming Model or APM) TaskFactory.FromAsync is also useful.

Mike Zboray
  • 39,828
  • 3
  • 90
  • 122