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.
CodePudding user response:
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
.
CodePudding user response:
If you really don't care about the result then there is nothing wrong with your approach (_=Task.Run();
). The approach using Task.FromResult
would only be needed if you did care about the result of the synchronous method.
The comment suggesting that you use Task.FromResult
might have been made so that you returned the value of the synchronous method and then choose whether to ignore it or do something with it outside of the async method. But there's nothing wrong with completely ignoring the result of sync method.