7

Is there a way to run async lambda synchronously? It is not allowed to modify lambda expression, it must be leaved as is.

Copy/paste example(it's 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) { ; }

Solution:

It is really a dilemma for me to accept one answer. I have tried out the solution from Stephen Cleary with NuGet package - works brilliant and is broad applicable, but an answer from dvorn to the question(as it's formulated ;)) is much easier.

Has dvorn changed the signature of lambda? No and Yes ;)

From MSDN:

Note that lambda expressions in themselves do not have a type because the common type system has no intrinsic concept of "lambda expression." However, it is sometimes convenient to speak informally of the "type" of a lambda expression. In these cases the type refers to the delegate type or Expression type to which the lambda expression is converted.

So both receive +1 and accepted answer by Stephen Cleary

6
  • aslmbda(lst).ToList() -> Wouldn't that stop deferred execution and force the list to be filled before returning to you?
    – Grisgram
    Apr 12, 2017 at 12:46
  • The returned type of aslambda(..) is void.
    – Rekshino
    Apr 12, 2017 at 12:48
  • aslambda(lst).Wait(); ? and instead of Thread.Sleep(100); await Task.Run(()=>{}); which has no sense just use await Task.Delay(100);
    – mrogal.ski
    Apr 12, 2017 at 13:03
  • @ m.rogalski: The returned type of aslambda(..) is void! It is not allowed to modify lambda expression.
    – Rekshino
    Apr 12, 2017 at 13:06
  • I didn't think that you could track when an async void is done. Am I wrong?
    – Equalsk
    Apr 12, 2017 at 13:11

2 Answers 2

6

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

Yes, but like all sync-over-async hacks, it's dangerous and won't work for all lambdas.

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

AsyncContext.Run(() => aslambda(lst));
10
  • 2
    This is who I was waiting for. Going to try this one out myself.
    – Equalsk
    Apr 12, 2017 at 13:30
  • The key is at the end of my SynchronizationContext article: async void methods generate special code to notify the SyncCtx when they start and finish. UI SyncCtxs just ignore these notifications. These notifications are normally only used in legacy ASP.NET WebForms async event handlers, so ASP.NET can detect when the handlers are all finished and the response is ready to be sent to the client. Apr 12, 2017 at 13:36
  • Thank you for giving the direction. I will try it out. It would be nice, if you could post a code sample(not with NuGet package).
    – Rekshino
    Apr 12, 2017 at 14:04
  • @Rekshino: No, it's too much code. You can check it out on GitHub, though. Apr 12, 2017 at 14:14
  • @StephenCleary There is a much easier approach to the problem (at least as it is formulated).
    – dvorn
    Apr 12, 2017 at 17:44
2

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.