Loading color scheme

How to guarantee data consistency in multi-threaded environments?

If you are working in a multi-threaded environment, sooner or later you will stumble upon the situation with data corruption or exceptions due to unsynchronized access to common variables. For example, if you modify some member variable from two threads at the same time, there will be the so-called race conditions and the data may be inconsistent. To aid such a situation, you need to use an atomic lock object. The lock object in C# protects access to the variable from the different threads. Only one thread may access data at the same time.

Let's move to an example:


public class ThreadTest{
	private object listLock = new object();
	
	
	
	
	public void ThreadFunction(object param)
	{
		lock(listLock)
		{
			// access to shared variable
		}
	
	
	}
	
}
Get all interesting articles to your inbox
Please wait