Synchronizing Thread Activities and Access to Data

Earlier we introduced one of the pitfalls of threading: deadlocks. In that example, it was easy to spot the problem, but that is not always the case. Before we look at other deadlock examples, we must introduce another pitfall of threading: race conditions.

Race Conditions

What happens when multiple threads access the same data at the same time? The answer is: indeterminate results. For this reason, you must synchronize access to global data from multiple threads. An example can help convey the message. Consider the following code in a new solution with a form that has a button:

long someCounter = 0; private void button1_Click(object sender, EventArgs e) { someCounter = 0; Thread t1 = new Thread(this.ThreadFirst1); ...

Get Microsoft® Mobile Development Handbook now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.