Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make an "old style" async method awaitable

Tags:

c#

async-await

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.

like image 999
Peregrine Avatar asked Feb 01 '13 12:02

Peregrine


People also ask

How do you create asynchronous method?

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 !

Can you await a non async method?

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.

What are the possible return types of asynchronous method?

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.

How do you create asynchronous method in C#?

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.


1 Answers

You could use a TaskCompletionSource:

var tcs = new TaskCompletionSource<TypeOfCallbackParameter>();

MyMethodAsync(..., r => tcs.SetResult(r));

return tcs.Task;
like image 107
Daniel Hilgarth Avatar answered Oct 22 '22 01:10

Daniel Hilgarth