有没有一种方法可以同步运行异步lambda? [英] Is there a way to run async lambda synchronously?
问题描述
有没有一种方法可以同步运行异步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 ;)
请注意,lambda表达式本身没有类型,因为 普通类型系统没有"lambda"的内在概念 表达."但是,有时非正式发言很方便 lambda表达式的类型".在这些情况下,类型是指 到lambda表达式所代表的委托类型或表达式类型 被转换.
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.
因此,两者都收到 +1 并由 Stephen Cleary
So both receive +1 and accepted answer by Stephen Cleary
推荐答案
有没有一种方法可以同步运行异步[void] lambda?
Is there a way to run async [void] lambda synchronously?
是的,但是像所有同步/异步黑客一样,这很危险,并且不适用于所有lambda.
Yes, but like all sync-over-async hacks, it's dangerous and won't work for all lambdas.
您必须具有自定义SynchronizationContext
才能检测到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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!