Monday, September 12, 2016

Multithread: Deadlock

A deadlock occurs when each of two threads tries to lock a resource the other has already locked. Neither thread can make any further progress.

Deadlock can be avoided by timeout mechanism.



if (Monitor.TryEnter(lockObject, 300)) {
    try {
        // Place code protected by the Monitor here.
DoSomething();
    }
    finally {
        Monitor.Exit(this);
    }
}
else {
    // Code to execute if the attempt times out.
}