简体   繁体   中英

Calling a Service with Async Await

I am looking at using the async await keywords in a call to a Service, but wondered if the await keyword is needed?

Modifying an example if found; What I would like to do is setup an async call to a service that gets on with the job, but doesn't need to wait for a response:

async Task CallService(InformationForService informationForService)
{
    var service = SetupService();

    // Does this need the await keyword?
    service.Doof(informationForService);

}

If you declare your function as async and that it returns Task then something in your code needs to return that type. I don't see anything in your code that does because you're not using the await keyword that would normally yield from your function while the call is being sent to the service and then continue from the following line when the call to the service responds.

If you don't care what the service returns, ignore it, but use the await keyword because that will allow your code to get on with other work while the service call is completed.

async Task<int> CallService(InformationForService informationForService)
{
    var service = SetupService();

    // Does this need the await keyword?
    await service.Doof(informationForService);

}

Also, note that if you're calling a service using WCF, you can issue a one-way call that completes once the last byte of the message is sent. Juval Lowy discusses one-way calls in this paper .

A method doesn't have to be async to be awaitable. There are many methods that return Task and can be used by await , even though they're not async .

I'm assuming that your service is a WCF service. In this case, if you (re-)generate a proxy using VS2012, for every method Doof on your service you'll get a DoofAsync method that will work with await .

Your CallService method does not need to be async ; you can just return the Task that you get from DoofAsync :

Task CallService(InformationForService informationForService)
{
  var service = SetupService();
  return service.DoofAsync(informationForService);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM