Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a Task from already asynchronous code?

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.

like image 618
xtravar Avatar asked Dec 09 '22 02:12

xtravar


1 Answers

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.

like image 112
Mike Zboray Avatar answered Dec 23 '22 20:12

Mike Zboray