16

What is the best way to handle a null task inside an async method?

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;
   }
}
4
  • 6
    what are you trying to do?
    – i3arnon
    Dec 18, 2014 at 16:22
  • 1
    I'd say public MyClass(Task task){if (task == null)throw new ArgumentNullException("task");..} Dec 18, 2014 at 16:35
  • 1
    Just don't accept null tasks. BTW, what are you trying to do? Wrapping a task and adding an execute method is very suspicious and possibly a code smell - trying to "control" when a task starts or executes, when there's no reason to. A Task itself is a class that abstracts when its delegate starts and executes, you don't need to add another class on top of it to do the same. Dec 19, 2014 at 8:47
  • 1
    I'm trying to understand the best practice for dealing with a potentially null task inside an async method. For the purpose of this discussion, let's assume that I've inherited a method that may allow null tasks and adding a null check in the constructor is not an option.
    – Robin
    Dec 19, 2014 at 15:35

3 Answers 3

26

You don't need to handle null tasks. Simply null check it:

public async Task Execute()
{
   if (task != null)
   {
       await task;
   }
}

Or even better, simply return the task since you're not adding anything after the await:

public Task Execute()
{
   return task;
}

If you want to return a completed task instead of null you can use Task.FromResult:

public Task Execute()
{
   return task ?? Task.FromResult(false);
}
3
  • 1
    "Task.FromResult(false)" works great when you have an overridable method that you can't make strictly abstract. Thanks for the excellent answer.
    – Xcalibur37
    Dec 5, 2015 at 18:28
  • Now that the Elvis operator is so common (.?) -- I have an extension method that uses this approach to make sure those await calls always work: public static Task<T> NullSafe<T>(this Task<T> task) => task ?? Task.FromResult(default(T)); -- so you can write code like var x = await (someObject?.DoTheThing()).NullSafe(); (Keep in mind, because of the way that the Elvis operator works, the parenthesis are significant in this statement.) Sep 27, 2018 at 16:08
  • 5
    "Task.CompletedTask" is an option, too Oct 17, 2019 at 20:36
16

Most asynchronous code is cleaner if tasks are never null. Instead of a null task, use Task.FromResult(0) or some such construct.

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

  public async Task ExecuteAsync()
  {
    await task;
  }
}

Or, if that's really all your ExecuteAsync is doing:

public Task ExecuteAsync()
{
  return task;
}

Note that the task is already running when the constructor is called, which makes the method name ExecuteAsync a misnomer. If you want the task to start when ExecuteAsync is called, then what you really want to store is a 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();
  }
}
0
0

What is the best way to handle a null task inside an async method?

Best practices typically include not allowing null parameters (unless the business rules require them).

public class MyClass
{
   private readonly Task _task;

   public MyClass(Task task) 
   { 
     if (task == null)
     {
       throw new ArgumentNullException("task");
     }

     this._task = task; 
   }

   public async Task Execute()
   {
      await this._task;
   }
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.