7

Can anyone point me to an example of calling a web service (not WCF) from C# using the new async/await syntax? Something like this:

public async Task<List<Widgets>> GetWidgetsAsync()
{
    var proxy = new Service1();
    var response = await proxy.GetWidgetsAsync();
    return response.Result;
}
svick
  • 236,525
  • 50
  • 385
  • 514
Sisiutl
  • 4,915
  • 8
  • 41
  • 54
  • 1
    Well what's generating the proxy for you? You've said you're not using WCF, but not what you *are* using. – Jon Skeet Mar 13 '14 at 17:21
  • 2
    This is an asmx web service. I'm using VS2012's Add Service Reference > Advanced > Add Web Reference – Sisiutl Mar 13 '14 at 18:31
  • The implementation of the web service is irrelevant to the client. Why don't you had a service reference instead? – Paulo Morgado Mar 14 '14 at 10:05
  • 1
    @PauloMorgado There are numerous services that are incompatible with the modern Service Reference implementation, like eTapestry's API http://www.4loopdev.com/etapestry-asp.net-example.html – Chris Moschini Sep 04 '14 at 16:58

3 Answers3

3

For a WCF service, when you add a reference and generate a proxy, there are options to generate either Task-based async methods or APM-based BeginXXX/EndXXX async methods.

I'm not sure about referencing the old-style XML Web service (asmx), but I think at least the second option should be there for it. In which case, you may wrap BeginXXX/EndXXX with Task.Factory.FromAsync, as described here.

Community
  • 1
  • 1
noseratio
  • 59,932
  • 34
  • 208
  • 486
0

There's a good explanation here:

Interop with Other Asynchronous Patterns and Types

In specific it seems this expample fits your (and my) needs:

 public static Task<string> DownloadStringAsync(Uri url)
 {
      var tcs = new TaskCompletionSource<string>();
      var wc = new WebClient();
      wc.DownloadStringCompleted += (s,e) =>
          {
              if (e.Error != null) 
                 tcs.TrySetException(e.Error);
              else if (e.Cancelled) 
                 tcs.TrySetCanceled();
              else 
                 tcs.TrySetResult(e.Result);
          };
      wc.DownloadStringAsync(url);
      return tcs.Task;
 }
F. Terenzi
  • 31
  • 1
  • 3
-3

Here is the official documentation for the Await and Async Asynchronous Programming with Async and Await (C# and Visual Basic). I followed their example, but I did not try with a Web service.

  • Question was specifically about Web Services, which don't provide async for you. You have to wrap them yourself if you want Task/async/await. – Chris Moschini Sep 04 '14 at 17:28