Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to choose methods for async calling in C#, how to propagate async

I have few async way of writing program questions. I am writing WCF service with some expensive methods, which are good candidates for async calling. But my questions about the implementations are:

  1. If I will create async method in the model, then I need mark service method as async to be able to await the model method, and change the return type to Task<originalType>. This will destroy service API convention consistency. What is the right way to go? Is it better to design the service interface as async Task returning methods even if some methods are not expensive and there is practically no reason to make it async?
  2. As I understood, only expensive method should be written as async, but in such case one half of the program will bee synchronous and the second one asynchronous. Is it right?
like image 716
Fanda Avatar asked Dec 14 '22 21:12

Fanda


1 Answers

If I will create async method in the model, then I need mark service method as async to be able to await the model method, and change the return type to Task. This will destroy service api convention consistency. What is the right way to go? Is it better to design the service interface as async Task returning methods even if some methods are not expensive and there is practically no reason to make it asnyc?

In WCF, when you change your method to return a Task<T>, you're actually not changing the WCF contract, as it can identify multiple asynchronous pattern for a single message, which means you can have all 3 patterns (Task, Sync and APM) in a single contract interface, and they would all relate to the same message.

From MSDN:

Clients can offer the developer any programming model they choose, so long as the underlying message exchange pattern is observed. So, too, can services implement operations in any manner, so long as the specified message pattern is observed.

This subject is covered to extend in Different forms of the WCF service contract interface and Asynchronously consume synchronous WCF service

As I understood, only expensive method should be written as async, but in such case one half of the program will bee synchronous and the second one asynchronous. Is it right?

As @l3arnon said, exposing an async api is not about how "expensive" the method is, it is about the work the method call is doing. if its true asynchronous work, such as accessing the file system, sending a network request, accessing an external data source, such as a database, then that is a fit candidate to expose an async api.

Combining these facts with WCF, you can expose both sync and async method via a single contract.

like image 64
Yuval Itzchakov Avatar answered Mar 15 '23 23:03

Yuval Itzchakov