How can I find the cause of a deadlock in a multithreaded C # program?

Mostly I have a C # server program (console application not in IIS), which sometimes comes to a standstill.

One strange thing, when I attach a debugger, I see 3 threads waiting to be locked, but without threads (using the threads window in the visual studio) inside the castle! What happens here ... I think the visual studio debugger is lying.

But anyway ... what methods or tools should I use?

thanks

+4
source share
5 answers

I would start by sending trace output every time a thread is about to enter / exit a critical section, as well as every time it successfully gets a lock. Use the System.Diagnostics.Trace class.

You can then determine from your output the trace in which there is actually a lock.

Typical trace code:

 Trace.WriteLine("Acquiring lock - foo"); lock (foo) { Trace.WriteLine("Acquired lock - foo"); // Do some stuff Trace.WriteLine("Releasing lock - foo"); } Trace.WriteLine("Released lock - foo"); 

Depending on how your program is structured, this may not be useful unless you include thread information in the trace output, for example:

 Trace.WriteLine(string.Format("Thread {0} - Acquiring lock - foo", Thread.CurrentThread.ManagedThreadId)); 

Once you figure out which thread has a lock, you can enter the debugger and see which lock it is waiting for, and then use the same trace output to find out who has another lock. In most cases, two threads are involved in a dead end, and this will allow you to find both of them.

+5
source

There is always WinDbg , but the learning curve can be a little complicated.

But see Brians for an excellent answer to this question: Detecting deadlocks in a C # application

+2
source

You can also use WinDbg with SOS.dll to find out where the deadlock is. Check out this article . The SOS.dll command in question is! Syncblk - it scans .NET threads that look for information about possible deadlocks.

+1
source

You probably have a race condition with your threads. One of your threads does not refuse to block and does not use it or does not allow anyone to use it. This also happens when a thread has a lock and is killed before abandoning it. You might want to check out some software deadlock solutions such as Sleeping Barber, Lamport Bakery, Dekker Algorithm, Peterson Algorithm or Dining Philosophers.

I don’t know how you manage your threads, so I can’t tell you which of the algorithms are the right solutions, but they are the most common solutions for concurrency and deadlocks inside operating systems, so they should solve your problem.

0
source

In short, Chess , a program from Microsoft to help solve these very problems.

From your site:

CHESS repeatedly runs parallel so that each run has a different rotation. If interleaving results in an error, CHESS can play interleaving to improve debugging. CHASS is available for both managed and native programs.

0
source

Source: https://habr.com/ru/post/1303413/


All Articles