Is there a way to run an asynchronous lambda synchronously?

Is there a way to run an asynchronous lambda synchronously? It is not possible to change the lambda expression, it should be displayed as is.

Copy / paste example (this is an abstraction):

var loopCnt = 1000000; Action<List<int>> aslambda = async (l) => { Thread.Sleep(100); await Task.Run(() => { }); for (int i = 0; i < loopCnt; i++) { l.Add(i); } }; var lst = new List<int>(); aslambda(lst); //This runs asynchronously if (lst.Count < loopCnt-100) { ; } 

Decision:

really a dilemma for making one answer. I tried the solution from Stephen Cleary with the NuGet package - it works brilliantly and is widely applicable, but the answer from dvorn to the question (as he formulated;)) is much simpler.

Did dvorn change the lambda signature? No and Yes;)

From MSDN:

Note that lambda expressions themselves are not type because the system of a general type does not have an internal concept of “lambda expression”. However, sometimes it is convenient to speak informally "type" of a lambda expression. In these cases, the type refers to the type of delegate or type of expression to which the lambda expression is converted.

So both get +1 and accept Stephen Cleary's answer

+7
multithreading c # lambda async-await
source share
2 answers

Is there a way to run an asynchronous [void] lambda synchronously?

Yes, but, like all sync-over-async hacks , this is dangerous and will not work for all lambdas.

You must have a custom SynchronizationContext to detect the completion of the async void (or lambda) method . This is not trivial, but you can use AsyncContext (available in the NuGet package Nito.AsyncEx.Context ):

 AsyncContext.Run(() => aslambda(lst)); 
+5
source share

The best solution: you cannot change the lambda, but you can change the type of the local variable to which it is assigned. Note that the native async lambda is not Action, but Func <Task>.

 ... Func<List<int>, Task> aslambda = async (l) => ... ... aslambda(lst).Wait(); ... 
+1
source share

All Articles