I cannot use the instance of my task (t) within my task’s action delegate in my code directly below. I get the following error:
Use of unassigned local variable ‘t’
Code:
Task t = Task.Factory.StartNew(() =>
{
MessageBox.Show(t.Id.ToString());
});
Now, it works if I do the following:
Task t = null;
t = Task.Factory.StartNew(() =>
{
MessageBox.Show(t.Id.ToString());
});
Could someone please explain why this is the case?
C# compiler does not know anything about
Task.Factory.StartNew. As far as the compiler is concerned, the access totcould happen at any time after callingStartNew, including the time beforethas been assigned.Your second code snippet has a race condition: if the task on a concurrent thread gets around to displaying message box before the assignment is complete, you will see a null reference exception.
Try this experiment:
Now replace the direct call of
Task.Factory.StartNewwith a call ofWrapperin your second snippet, and watch the program crash.