基于异步注释执行C#Lambda表达式

Cra*_*ham 5 .net c# lambda asynchronous functional-programming

我试图在下面找到一个优雅的Execute(..)方法实现,它接受一个lambda表达式.我正在努力做甚么可能吗?看起来我应该能够,因为编译器将允许我传递这样的lambda表达式(以Action的形式).

    static void Main(string[] args)
    {
        // This should execute SomeOperation() synchronously
        Execute(() => SomeOperation());

        // This should begin execution of SomeOperationAsync(), but not wait (fire and forget)
        Execute(() => SomeOperationAsync());

        // This should await the execution of SomeOperationAsync() (execute synchronously)
        Execute(async () => await SomeOperationAsync());
    }
Run Code Online (Sandbox Code Playgroud)

在给定这些规范的情况下,您将如何实现上述Execute方法?

Jon*_*eet 4

可以检查您所传递的委托背后的方法是否带有 - 注释,AsyncStateMachineAttribute但说实话,我不会。使用这样的实现细节只是自找麻烦。

相反,我有一个单独的重载,ExecuteAsyncDelegate其中使用了 aFunc<Task>而不仅仅是Action. 当然,您需要小心您在其中所做的事情 - 您很可能不想仅仅阻止正在执行的线程。您可能还想考虑将设为异步方法。(目前还不清楚你的Execute方法除了调用委托之外还有什么用途 - 大概它在某个地方增加了价值。)

例如,假设您实际上这样做是为了计时。你可能有:

static async Task<TimeSpan> BenchmarkAsync(Func<Task> func)
{
    Stopwatch sw = Stopwatch.StartNew();
    await func();
    sw.Stop();
    return sw.Elapsed;
}
Run Code Online (Sandbox Code Playgroud)