Avoid deadlocks:
Lock an object in the same order in all threads
Locks the lock object required in all calls to the same location in the code, releasing all objects immediately in the call to the uprising
Lock objects as little as possible and as short as possible
If you must lock multiple objects, make sure that all locks are successful and terminate them if they have not finished processing. The Monitor.TryEnter method can be used to do this, the following code
if (Monitor.TryEnter (employee))
{
if (Monitor.TryEnter (payroll))
{
Processing here
}
Else
Couldn ' t lock payroll
Monitor.Exit (employee);
}
------------------------------------------------
Avoiding race conditions
Keep the work that must be done sequentially in one thread, rather than spreading them to multiple threads
If a thread must be completed in another county before it can continue, use Thread.Join to force the second thread to wait for the first thread
If the snort is using a shared resource couple on a thread and the second thread can use the shared resource, use a synchronization object like monitor or mutex to control access to that resource
Handling Threading Issues