Suppose in the depths of the program, there is a method:

public static string WriteSomeMethod(string Somedata){ //Бурная долгая деятельность return SomeData2; //Имитация возвращения данных } 

At the same time, we want our program not to hang when calling this method, so we write another one:

 public static async Task<string> WriteSome(string Somedata){ return await Task.Run(()=> WriteSomeMethod(Somedata)); } 

If we try to call var tmpdata = WriteSome("123"); somewhere in another code var tmpdata = WriteSome("123"); then we see that var is not really a string , but Task<string> . To get a string, we need to do this: var tmpdata = await WriteSome("123"); and make this method asynchronous.

Making it asynchronous, you will need to make the result of its work Task, => you need to repeat it until the moment when we rest on the event handler and make it asynchronous. How to avoid this, and just return a string from WriteSome right away?

PS Sometimes there will be not a string, but a class, with a ton of variables.

  • return Task.Run(() => WriteSomeMethod(Somedata)).GetAwaiter().GetResult(); - Bulson pm
  • @Bulson мы хотим, что бы наша программа не вешалась при вызове этого метода - tym32167 pm
  • You want to make the handler synchronous and at the same time, so that the execution of the method does not block the UI? And what's the problem with using an asynchronous handler? He by the way can be async void . - John

1 answer 1

If you want to use asynchrony and have maximum benefit from this, then yes, from the very bottom to the top, while the calling code is interested in the results of the called code, you will have to change method signatures everywhere and make methods asynchronous up the stack. Not only that, this design

 public static async Task<string> WriteSome(string Somedata){ return await Task.Run(()=> WriteSomeMethod(Somedata)); } 

It does not make sense, since this is an extra wait, you have only 1 task inside the method, the results of which you only want to forward to the top? Do this, get fewer generated state machines as a result:

 public static Task<string> WriteSomeAsync(string Somedata){ return Task.Run(()=> WriteSomeMethod(Somedata)); } 
  • In the comments you correctly noticed. GetAwaiter().GetResult() is a truly blocking call. I remembered him because in the best practices such a call was called more correct than Wait() if it is necessary to call the asynh. Method synchronously. - Bulson pm