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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With