![](/img/trans.png)
[英]Why doesn't a method containing an async lambda need to be Async itself?
[英]Why doesn't an async LINQ Select lambda require a return value
我正在阅读Stephen Cleary的Concurrency in C#
的Concurrency in C#
其中有一个例子让我困惑了一段时间。
通常,LINQ Select方法需要一个lambda方法,该方法返回结果集合的值。
在第30页的书中有一个示例,其中lambda不返回任何内容,但是,代码编译并运行良好:
static async Task<int> DelayAndReturnAsync(int val)
{
await Task.Delay(TimeSpan.FromSeconds(val));
return val;
}
static async Task ProcessTasksAsync()
{
// Create a sequence of tasks
Task<int> taskA = DelayAndReturnAsync(2);
Task<int> taskB = DelayAndReturnAsync(3);
Task<int> taskC = DelayAndReturnAsync(1);
var tasks = new[] { taskA, taskB, taskC };
var processingTasks = tasks.Select(async t =>
{
var result = await t;
Trace.WriteLine(result);
// Note: nothing is returned
}).ToArray();
// Await all processing to complete
await Task.WhenAll(processingTasks);
}
// Outputs:
// 1
// 2
// 3
问题是这部分:
var processingTasks = tasks.Select(async t =>
{
var result = await t;
Trace.WriteLine(result);
// Note: nothing is returned
}).ToArray();
为什么是这样? 这是推荐的方法吗?
更新:
这种行为记录在哪里?
这就像编写一个不返回值的异步方法,但使用Task
来表示完成:
public async Task FooAsync()
{
Console.WriteLine("Before");
await Task.Delay(1000);
Console.WriteLine("After");
}
作为异步匿名函数,那将是:
Func<Task> foo = async () =>
{
Console.WriteLine("Before");
await Task.Delay(1000);
Console.WriteLine("After");
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.