6

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.

Peregrine
  • 4,287
  • 3
  • 17
  • 34
  • 2
    In a Portable Class Library or .NET 4.5 you could use TaskFactory.FromAsync (http://msdn.microsoft.com/en-us/library/dd321469.aspx) - I don't know of a simple equivalent for WP7. There may be a support library which has something equivalent. – Jon Skeet Feb 01 '13 at 12:10
  • 2
    I thought FromAsync was only for methods defined as BeginXXX, EndXXX pairs? – Peregrine Feb 01 '13 at 12:11
  • There are various FromAsync overloads. I may not have linked to the most appropriate one. – Jon Skeet Feb 01 '13 at 12:14
  • @JonSkeet: Could you link to the correct overload? As far as I am seeing it, all overloads require an `IAsyncResult` - which the OP doesn't have. Am I missing something? – Daniel Hilgarth Feb 01 '13 at 12:17
  • Take a look at answers this question: [General purpose FromEvent method](http://stackoverflow.com/questions/12865848/general-purpose-fromevent-method). It's not exactly what you're looking for, but might be useful. – Nick Hill Feb 01 '13 at 12:17
  • @DanielHilgarth: Ah, it's not *that* old-style... it's the event-based version. Right, in that case the FromEvent question that Nikolay linked to is the right approach. It would have been clearer IMO if the OP had given full signatures. (The Begin/End style *also* take a callback, of course.) – Jon Skeet Feb 01 '13 at 12:22

1 Answers1

8

You could use a TaskCompletionSource:

var tcs = new TaskCompletionSource<TypeOfCallbackParameter>();

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

return tcs.Task;
Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443