【问题标题】:Why doesn't an async LINQ Select lambda require a return value为什么异步 LINQ Select lambda 不需要返回值
【发布时间】:2019-07-20 05:42:58
【问题描述】:

我正在阅读 Stephen Cleary 的 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();

这是为什么?这是推荐的方法吗?

更新:

这种行为记录在哪里?

【问题讨论】:

    标签: c# linq asynchronous select


    【解决方案1】:

    这就像写一个不返回值的异步方法,而是使用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");
    };
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    • 2020-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-16
    相关资源
    最近更新 更多