For example let’s say I’m writing a method with the below signature (C#4 so no async keywords):
public Task Refresh();
It will call one method (which also returns a Task) to perform the comms work, and then run a task continuation to update some internal state based on the retrieved data. e.g:
public Task Refresh()
{
Task<MyData> commsTask = datasource.LoadData();
Task handleDataTask = commsTask.ContinueWith( HandleNewData );
return ?;
}
If I return the handleDataTask it’s completion state correctly tracks the result of the ‘Refresh’ operation, but it doesn’t correctly report it’s started state.
I can wrap both in a new Task.Factory.StartNew and create them as child tasks, but it seems wasteful to spool up a new thread just for the sake of linking some task continuations.
Surely there is a neat efficient way to do this with the TPL?
Usually,
Task.Statusis only used to find out about the final state. You can’t rely on the task beeingStartedanyway because that state might change any time.Because of that fact it does not matter if the task you return has a “strange” state until it is completed. Only the three completed states (
Completed,Canceled,Faulted) matter.