If I have an asynchronous method with a callback
MyMethodAsync( <Input Parameters ...>, Callback);
how can I make it awaitable?
[This method is for windows phone 7, but should be equally applicable to any similar c# construct]
DNSEndpoint Endpoint = ...
NameResolutionCallback Callback = (nrr) => { ... }
DeviceNetworkInformation.ResolveHostNameAsync(Enpoint, Callback, null);
I want to put an awaitable wrapper around this call, so I wait for the callback to complete before continuing with the next command.
The first step is to add the async keyword to the method. It appears in the method signature in the same way that the static keyword does. Then, we need to wait for the download using the await keyword. In terms of C# syntax, await acts as a unary operator, like the !
You can not use the await keyword in a regular, non-async function. JavaScript engine will throw a syntax error if you try doing so.
Async methods can have the following return types: Task, for an async method that performs an operation but returns no value. Task<TResult>, for an async method that returns a value. void , for an event handler.
A method in C# is made an asynchronous method using the async keyword in the method signature. You can have one or more await keywords inside an async method. The await keyword is used to denote the suspension point. An async method in C# can have any one of these return types: Task, Task<T> and void.
You could use a TaskCompletionSource
:
var tcs = new TaskCompletionSource<TypeOfCallbackParameter>();
MyMethodAsync(..., r => tcs.SetResult(r));
return tcs.Task;
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