I am trying to find an elegant implementation of the Execute(..) method below that takes in a lambda expression. Is what I'm trying to do even possible? It seems like I should be able to because the compiler will allow me to pass such a lambda expression (in the form of an Action).
我正在尝试寻找执行(.. .)方法的一个优雅的实现,它包含一个lambda表达式。我想要做的事情是可能的吗?看起来我应该可以,因为编译器允许我传递这样的lambda表达式(以操作的形式)。
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());
}
How would you implement the Execute method above given these specifications?
您将如何实现上面给出的这些规范的执行方法?
1 个解决方案
#1
4
You could check whether the method underlying the delegate you've been passed is annotated with the AsyncStateMachineAttribute
- but to be honest, I wouldn't. It's just asking for trouble, using an implementation detail like that.
您可以检查您所传递的委托的底层方法是否带有AsyncStateMachineAttribute—但是说实话,我不会这样做。使用这样的实现细节只是自找麻烦。
Instead, I'd have a separate overload of ExecuteAsyncDelegate
which took a Func<Task>
instead of just Action
. You need to be careful about what you do within that, of course - you quite possibly don't want to just block the executing thread. You may want to consider making this an async method as well. (It's not clear what your Execute
method is meant to do other than just call the delegate - presumably it's adding value somewhere.)
相反,我将有一个单独的ExecuteAsyncDelegate重载,它使用Func
For example, suppose you were actually doing this for timing purposes. You might have:
例如,假设您实际上是为了计时目的而这么做的。你可能有:
static async Task<TimeSpan> BenchmarkAsync(Func<Task> func)
{
Stopwatch sw = Stopwatch.StartNew();
await func();
sw.Stop();
return sw.Elapsed;
}
#1
4
You could check whether the method underlying the delegate you've been passed is annotated with the AsyncStateMachineAttribute
- but to be honest, I wouldn't. It's just asking for trouble, using an implementation detail like that.
您可以检查您所传递的委托的底层方法是否带有AsyncStateMachineAttribute—但是说实话,我不会这样做。使用这样的实现细节只是自找麻烦。
Instead, I'd have a separate overload of ExecuteAsyncDelegate
which took a Func<Task>
instead of just Action
. You need to be careful about what you do within that, of course - you quite possibly don't want to just block the executing thread. You may want to consider making this an async method as well. (It's not clear what your Execute
method is meant to do other than just call the delegate - presumably it's adding value somewhere.)
相反,我将有一个单独的ExecuteAsyncDelegate重载,它使用Func
For example, suppose you were actually doing this for timing purposes. You might have:
例如,假设您实际上是为了计时目的而这么做的。你可能有:
static async Task<TimeSpan> BenchmarkAsync(Func<Task> func)
{
Stopwatch sw = Stopwatch.StartNew();
await func();
sw.Stop();
return sw.Elapsed;
}