Multi-Threading is not new to the programming world. We use multi-threading in our application to enhance the throughput and responsiveness of the application, but with concurrent access of certain resources, the application is prone to deadlocks and Race conditions. The post will guide you through how to avoid such kind of scenarios. What is a deadlock?When two or more threads are trying to lock a resource which is already exclusively locked by some other thread, deadlock can occur. In this case the two thread keep on waiting but no one gets the exclusive lock on the resource. To solve the problem you can use Monitor.TryEnter to specify the timeout seed value which will ensure that the Thread will not wait infinitely rather will wait until the timeout is reached, or you can use shared lock using ReaderWriterLock class. Read more from here.What is Race Condition?A Race Condition is situation when two or more Thread tries to access a resource at a time leaving an inconsistent state of the program.Say for instance,
Thread 1 checks the value of X being 1;
Thread 2 checks the value of X being 1;
Thread 1 tries to increment the value of X to 2; Invokes x = x + 1; // 2
Thread 2 tries to increment the value of X to 2; invokes x = x + 1 // 3 (inconsistent) Thus thread 2 is in inconsistent state as it tries to increment the value of X to 2 while it gets 3.Race condition can be avoided using a class called Interlocked. The class Interlocked exposes a number of methods that allows ThreadSafe access to a value and ensures inconsistent thread does not appear in the program. In this case, it will ensure that the value of X is 1 for every thread when it increments the value otherwise loaded again. To Increment/decrement a value of a variable :Interlocked.Increment(ref x); //increments the value by 1
Interlocked.Decrement(ref x); //decrements the value by 1
Interlocked.Add(ref x, 10); //adds value 10 to x
Read more: Daily .Net Tips
QR:
Thread 1 checks the value of X being 1;
Thread 2 checks the value of X being 1;
Thread 1 tries to increment the value of X to 2; Invokes x = x + 1; // 2
Thread 2 tries to increment the value of X to 2; invokes x = x + 1 // 3 (inconsistent) Thus thread 2 is in inconsistent state as it tries to increment the value of X to 2 while it gets 3.Race condition can be avoided using a class called Interlocked. The class Interlocked exposes a number of methods that allows ThreadSafe access to a value and ensures inconsistent thread does not appear in the program. In this case, it will ensure that the value of X is 1 for every thread when it increments the value otherwise loaded again. To Increment/decrement a value of a variable :Interlocked.Increment(ref x); //increments the value by 1
Interlocked.Decrement(ref x); //decrements the value by 1
Interlocked.Add(ref x, 10); //adds value 10 to x
Read more: Daily .Net Tips
QR:
0 comments:
Post a Comment