Consider the below code:
private Task _task;
private void M()
{
_task = Task.Factory.StartNew(() => {
// Do work
_task = null;
}, TaskCreationOptions.LongRunning);
}
I know that Task.Factory.StartNew
creates a new Task
and schedules it for execution, then returns that Task
. I'm wondering whether the above logic is faulty. Is there a chance that the return value of Task.Factory.StartNew
will be assigned to _task
later than the execution of the passed in lambda?
Or is there some logic implemented in StartNew
that prevents this?
I can certainly imagine a scenario where a context switch happens inside the StartNew
, executing the passed in lambda setting _task
to null
, then the return value overriding it with the non null
Task
instance. Am I correct in this assumption?