I'm implementing a method Task<Result> StartSomeTask()
and happen to know the result already before the method is called. How do I create a Task<T> that has already completed?
This is what I'm currently doing:
private readonly Result theResult = new Result();
public override Task<Result> StartSomeTask()
{
var task = new Task<Result>(() => theResult);
task.RunSynchronously(CurrentThreadTaskScheduler.CurrentThread);
return task;
}
Is there a better solution?
ValueTask
for completed tasks (i.e. for values you already have so that code is essentially synchronous), which will save you an allocation. – nawfal