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();
}
}
public MyClass(Task task){if (task == null)throw new ArgumentNullException("task");..}