简体   繁体   English

为什么异步LINQ Select lambda不需要返回值

[英]Why doesn't an async LINQ Select lambda require a return value

I am reading Concurrency in C# by Stephen Cleary in which there is an example that has puzzled me for a while. 我正在阅读Stephen Cleary的Concurrency in C#Concurrency in C#其中有一个例子让我困惑了一段时间。

Normally the LINQ Select method requires a lambda method that returns the value for the result collection. 通常,LINQ Select方法需要一个lambda方法,该方法返回结果集合的值。

In the book on page 30 there is an example where the lambda doesn't return anything, but nevertheless, the code compiles and runs fine: 在第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

The question is about this part: 问题是这部分:

var processingTasks = tasks.Select(async t => 
   {
      var result = await t;
      Trace.WriteLine(result);
      // Note: nothing is returned
   }).ToArray();

Why is this? 为什么是这样? Is it a recommended approach? 这是推荐的方法吗?

UPDATE: 更新:

Where is this behaviour documented? 这种行为记录在哪里?

It's just like writing an async method that doesn't return a value, but uses a Task to indicate completion: 这就像编写一个不返回值的异步方法,但使用Task来表示完成:

public async Task FooAsync()
{
    Console.WriteLine("Before");
    await Task.Delay(1000);
    Console.WriteLine("After");
}

As an async anonymous function, that would be: 作为异步匿名函数,那将是:

Func<Task> foo = async () =>
{
    Console.WriteLine("Before");
    await Task.Delay(1000);
    Console.WriteLine("After");
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM