简体   繁体   中英

Calling Async Method from Sync Method

I see a lot of questions about calling asyc methods from sync ones, like here: How to call asynchronous method from synchronous method in C#?

I understand the solutions however, experimentally, I am seeing that I don't need to add a .Wait() or Task.Run(async () => await MyAsyncMethod()) for it to run synchronously. I have a get method that pulls information from a DB.

My code is below and when I run, it waits at var task = GetItemAsync() and I get the correct result from the DB. I find it hard to believe that the DB call could come back before the code would move on which seems to imply that it ran synchronously. Am I missing something?

public object GetItem()
{
     var task = GetItemAsync();
     var result = task.Result;

     return result
}

See The docs on Task<>.Result

System.Threading.Tasks.Task.Result is a blocking call that waits until the task finishes. So it has a built in wait call essentially.

In the remarks section of that microsoft doc:

Accessing the property's get accessor blocks the calling thread until the asynchronous operation is complete; it is equivalent to calling the Wait method.

It's unfortunate that Microsoft did not reflect this in the name of the accessor because it's an extremely critical side effect of this accessor.

The only right way to call awaitable(method which returns Task ) method is to await it. But you can await only within the method which returns Task . In legacy code it happens you cannot change the method signature because you have too many reference and you need to basically refactor entire code base. So you have these options:

.Result
.Wait()
.GetAwaiter().GetResult()

Neither of those are good. All of them are going to block the thread . But if you cannot change the method signature to await the execution, I would pick the last option - GetAwaiter().GetResult() becasue it will not wrap the exception into AggregateException

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