Suppose we have a class within which there are many synchronous methods:

public class A { public int Return5() => 5; public string ReturnString() => "string"; } 

Is it possible to create a wrapper class for asynchronous synchronous methods? That is, for each synchronous method to create the same only with the returned Task<> type and at the end of the method name, the Async ending was added. Let's say it looks like this:

 var asyncA = new AsyncClass<A>; var result = await asyncA.ReturnStringAsync(); 

    1 answer 1

    Technically possible, but it is usually not necessary.

    If the bottleneck of the method is CPU consumption, it is better to set the synchronous interface. Then clients can easily start the task asynchronously themselves:

     var five = await Task.Run(() => a.Return5()); 

    And they may not run asynchronously if the method does not need it.

    That is, in this case, simply expose the synchronous method, customers themselves can easily turn it into asynchronous.


    But if the method does not take a thread for its execution (for example, it loads something from the Internet, using async functions), then you need to set only the asynchronous method. Accordingly, you will not be able to set a synchronous method, unless it is artificially created through Task.Wait() (which is not necessary again, because the client can do it himself if he wishes).


    Additional reading on the topic from one of the key developers of asynchronous features C #: Should I expose synchronous wrappers for asynchronous methods?


    How to technically make an asynchronous wrapper? For example, via Task.Run :

     public class AsyncA { private A a = new A(); public Task<int> Return5Async() => Task.Run(() => a.Return5()); // и т. д. } 
    • In general, the idea is clear, but for educational purposes it is interesting to me how such an effect could be achieved. - Lightness
    • @Lightness: Added in response. The wrapper will have to be written for each class separately (and how can you create an unknown number of methods in advance?) - VladD
    • And I was hoping that there are some options, now I will know that there is not. Thank! - Lightness
    • @Lightness: Please! - VladD
    • one
      Well, you can always use templates, there are all sorts. File parsing -> search for types or tagged with an attribute -> generation of wrappers. Do not forget to mark classes as partial, so that methods are easily and conveniently accessible from the class itself. - Monk