Word of caution while using shared variables.
If you see my previous example, you will see that my calculate PI returns a variable j which is declared local to the function and not the task. So that variable is a shared variable between the UI thread and the Task T thread.
But there are certain things we need to keep in mind while using shared variables since it might lead to Race conditions. Let me illustrate that by a diagram
Look carefully at the below diagram. We have two tasks T and T_new. T operates on a value called variable which is shared between the UI Thread, T_new Thread and itself. So basically what is shown, is that first T operates and populates the value of the “variable”. Then AFTER it finishes, Task T_new reads the value of the variable and computes “Result”. Now the problem here is there is absolutely no guarantee that T will finish before T_New. It might happen that when T_new reads “variable” before T updates its value!!!!
This is a race condition, since both the tasks race to access the variable! We cannot predict beforehand , which task will access the “variable” first!
Sometimes, race condition error is difficult to catch as in Debug mode it may not appear. In Release mode, NET optimizes a lot of routines hence the race condition error may appear then. It is mostly platform specific and hence very difficult to catch.
Now coming back to our calculate PI program, it is free from any Race Condition. The reason being the variable j is first accessed in the Tast T thread. Then in the next thread it is accessed again. But since we have the keyword “continue with”, it can only work when task T has finished updating “j”, hence there isn’t any race condition.
So what do we when we need to wait for a Task to finish before starting another task ?
We use the wait keyword. More on that in the next section