在异步方法中处理空任务的最佳方法是什么?

Rob*_*bin 4 .net c# task-parallel-library async-await

在方法中处理null任务的最佳方法是什么async

public class MyClass
{
   private readonly Task task;
   public MyClass(Task task) { this.task = task; }

   public async Task Execute()
   {
      if (task == null)
      {
         await Task.Yield(); /* Is this the best way? */
         return;
      }
      await task;
   }
}
Run Code Online (Sandbox Code Playgroud)

i3a*_*non 15

您不需要处理null任务.只需检查它:

public async Task Execute()
{
   if (task != null)
   {
       await task;
   }
}
Run Code Online (Sandbox Code Playgroud)

或者甚至更好,只需返回任务,因为你没有在以下之后添加任何内容await:

public Task Execute()
{
   return task;
}
Run Code Online (Sandbox Code Playgroud)

如果要返回已完成的任务而不是null可以使用Task.FromResult:

public Task Execute()
{
   return task ?? Task.FromResult(false);
}
Run Code Online (Sandbox Code Playgroud)

  • “Task.CompletedTask”也是一个选项 (3认同)

Ste*_*ary 11

如果任务永远不为null,则大多数异步代码都更清晰 而不是null任务,使用Task.FromResult(0)或一些这样的构造.

public class MyClass
{
  private readonly Task task;
  public MyClass(Task task) { this.task = task ?? Task.FromResult(0); }

  public async Task ExecuteAsync()
  {
    await task;
  }
}
Run Code Online (Sandbox Code Playgroud)

或者,如果这真的ExecuteAsync是你所做的一切:

public Task ExecuteAsync()
{
  return task;
}
Run Code Online (Sandbox Code Playgroud)

请注意,在调用构造函数时,任务已在运行,这使得方法名称ExecuteAsync用词不当.如果你想在调用时启动任务ExecuteAsync,那么你真正想要存储的是Func<Task>:

public class MyClass
{
  private readonly Func<Task> func;
  public MyClass(Func<Task> func) { this.func = func ?? () => Task.FromResult(0); }

  public async Task ExecuteAsync()
  {
    await func();
  }
}
Run Code Online (Sandbox Code Playgroud)