For some heavy caching / high performance path in my project I need to "cast" a Task<X>
to a Task<Y>
type - see here.
I used the ContinueWith
solution, but I noticed that even when my original task is in a RanToCompletion
state, the ContinueWith
still returns a Task
that is WaitingToRun
.
var task = Task.FromResult("cheese");
var test = task.ContinueWith(x => (object)x);
Console.WriteLine(test.Status); // WaitingToRun
Console.ReadLine();
For reasons out of the scope of this question, this gives me some extra cost further down the line.
If I do the following, my very specific problem seems to be fixed and it will directly return a CompletedTask, otherwise it does the normal logic.
if ( task.IsCompletedSuccessfully )
return Task.FromResult((object)task.Result);
else
return task.ContinueWith(x => (object)x);
Is it safe to add this "happy path" to my logic?
Because this path is not in the normal ContinueWith
logic I am afraid I am missing something and this will bite me when running in production in a high concurrent environment.