问题描述
有没有一种方法可以同步运行异步lambda?不允许修改lambda表达式,必须将其保留原样.
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) { ; }
解决方案:
接受一个答案对我来说是一个真正的难题.我已经尝试使用NuGet软件包尝试了 Stephen Cleary 的解决方案-效果很好,适用范围很广,但是 dvorn 对这个问题的回答(因为它是提法的;)是容易得多.
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.
dvorn 是否更改了lambda的签名?否,是;)
Has dvorn changed the signature of lambda? No and Yes ;)
因此,两者都收到 +1 并由 Stephen Cleary
So both receive +1 and accepted answer by Stephen Cleary
推荐答案
是的,但是像所有同步/异步黑客一样,这很危险,并且不适用于所有lambda.
Yes, but like all sync-over-async hacks, it's dangerous and won't work for all lambdas.
您必须具有自定义SynchronizationContext
才能检测到方法(或lambda).这很简单,但是您可以使用我的 AsyncContext
(可在NuGet软件包Nito.AsyncEx.Context
中找到):
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));
这篇关于有没有一种方法可以同步运行异步lambda?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!