简体   繁体   中英

How to call a synchronous method from an asynchronous method

In my application there is an async method which calls an API and from the result I need to send to a queuing system. I don't need to await the result. But the method to push the message is a synchronous one. What's the best way we can implement it? I wrote _=Task.Run(); but I got a comment to change to Task.FromResult which I think has the value of Task.Result which is not a good approach as I don't care about the result of the Task. 在此处输入图像描述

In the general case: just call it . Calling a sync method from async: absolutely fine, no problem.

If the problem is you don't want to delay the async code, then any choice of Task.Run , ThreadPool.QueueUserWorkItem , or for very long operations: new Thread . The fact that you don't observe the result isn't a problem, as long as it doesn't fault - so: make sure you handle any exceptions, even if that means adding your own wrapper later for a try / catch .

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