Пользовательский элемент управления. Создание клиентского приложения. Развитие серверного проекта, страница 16

Synchronizing threads

When we employ free multithreading in the application, we exposed the application to great risk of corrupting the data, because more than one thread can access a variable at a time and try to write data into the same variable. The way we can prevent this is through using synchronization. Synchronization is the process of ensuring that only one thread can access a given variable at a time. There are many ways of synchronizing thread and two of them are through Monitor class and lock keyword.

We use the Monitor class when we want to lock an object and perform some operations over it with one thread a time. We use the Enter() method of the Monitor class: 

Monitor.Enter(object);

We release the object through the Exit() method of the Monitor class:

Monitor.Exit(object);

We can have the following situation:

static object object1 = ”Experiment”;

Thread t1 = new Thread (new ThreadStart(method1));

Thread t2 = new Thread (new ThreadStart(method2));

t1.Start();

t2.Start();

public static void method1()

{

if (Monitor.TryEnter(object1))

{

Monitor.Enter(object1);

//Some code to be done

Monitor.Exit(object1);

}

else

{ }

}

public static void method2()

{

if (Monitor.TryEnter(object1))

{

Monitor.Enter(object1);

//Some code to be done

Monitor.Exit(object1);

}

else

{ }

}

Here at first one of the thread locks the object and start doing its job. At some time the other thread is going to start and first tries if the object is free. If the object is still in the possession of the previous thread the acquiring thread will simply go to the else statement. When the object gets free the waiting thread will take it and lock it for itself.

lock() keyword

We use the lock() keyword when we want to lock a variable:

public static void Method()

{

lock(variable1);

{

//Some code to be done

}

}

What the lock does is to create a mutual exclusive lock around the variable, so no other thread can access it while it is in the lock() block. Even if the thread locked the variable loses its time slice, and another thread comes to the picture the newcomer will not have access to the locked variable.

Synchronization issues (Professional C# 2nd Edition; Wrox Press Ltd, May 2002)

¨  Do not overuse synchronization. Any lock in the application creates overhead when locks the variable or the object and it releases. So this can hurt the performance of the application if there are too many locks.

¨  Deadlocks. A deadlock is a bug when two threads are trying to access resources, which are locked by each other:

One thread has reached this code and has locked a:

lock(a)

{

//code

lock(b)

{

//code

}

}

The other thread has reached here and has locked b

lock(b)

{

//code

lock(a)

{

//code

}

}

No one of the threads is going to release its object and they will wait infinitely for the resource they need. Deadlocks can be avoided by claiming the resources you will need in the beginning of the code and locking them at first.

Bibliography:

¨  Aitken, Peter G.; Get Started with Multithreading in .NET; http://www.devx.com/dotnet/article/7003; 2002

¨  Bosch, Peter; A Beginner’s Guide to Threading in C#;

¨  http://builder.com.com/article.jhtml?id=u00220020531pcb01.htm; 05/31/2002

¨  Ewing, Greg; Using threads; http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dv_vstechart/ html/vbtchusingthreads.asp; March 2002

¨  Hinton, Ben; Threading in .NET Part I; http://www.dotnetjunkies.com/tutorials.aspx?tutorialid=296; 3/22/2002

¨  Robinson, Simon; Allen, K. Scott; Cornes, Ollie; Glynn, Jay; Greenvoss, Zach; Harvey, Burton; Nagel, Christian; Skinner, Morgan; Watson, Karli; C# and the Bases Classes, p322-334; Professional C# 2nd Edition; Wrox Press Ltd, May 2002