How to forget synchronization context in asynchronous methods in C #

Let's say I want to write an asynchronous method M. I don’t know what synchronization context will be used (UI, ASP.NET, console application, etc.) to call it. I would like to make this method as easy to use as possible. This means that everyone should be able to call him synchronously, referring to a member of the result of the returned task.

public async Task<int> M() { // lot of calling of helper methods including awaits, etc. // helper methods not owned by me // ... return 42; } // this should be safe to do from any synchronization context int result = M().Result; // Synchronously wait 

The problem is that the synchronization context of the calling object of method M seeps into calls to M. If any of them wants to continue the transfer in the context of synchronization, then it may go into a dead end (for example, when using the UI synchronization context).

One way to forget the synchronization context when calling M is to transfer the contents of M to Task.Run. However, this will cause a jump in the thread, including in cases where all tasks inside M are completed, and everything can synchronously work in one thread without context switches. Is there a better solution to forget the thread synchronization context? Or am I missing something that would make this question inappropriate?

+4
source share
1 answer

I would like to make this method as easy to use as possible. This means that everyone should be able to call it synchronously by contacting a member of the result of the returned task.

There is no easy way to create a synchronous wrapper for an asynchronous method . It is best to let asynchronous methods be asynchronous.

You can use ConfigureAwait(continueOnCapturedContext: false) to cancel the context, but in your case it will not be better than Task.Run , since you cannot change the methods called by M

+3
source

Source: https://habr.com/ru/post/1483509/


All Articles