Search code examples
c#asp.net.netc#-4.0deadlock

How to find out deadlock and prevent it in C#


I had an interview just 5 minutes back, I didn't answer 3 questions, could someone please help me.

Question:

How to look for deadlock scenarios in Multithreaded application function and prevent it ?

Answer I gave:

I gave definition of deadlock and lock, mutex, monitor, semaphore. He told me, that these are tools, but how to look for a deadlock scenario as because when we use these tools blindly, it costs the performance he said :(

Please help me understand this.


Solution

  • Performance analysis tools can be also helpful in identifying deadlocks, among others. This question will provide some insight in this topic: C#/.NET analysis tool to find race conditions/deadlocks .

    Visual analysis of the code and the proper using of locks is useful also (you should be able to detect potential problems in code while inspecting it), but can be very difficult for complex applications. Sometimes the deadlocks are visible only when you run the code, not simply by inspecting the code.

    I don't know too much of your interviewer. Some may want to see how much you know of locking standards/guideliness, some may want to see if you know how to use your tools, some may want both. In the company I work at, for example, the use of tools (expecially the ones we already own and use) is highly appreciated. But that does not imply one should not have the skills that would prevent coding deadlocks in the first place.

    Locking something just for the sake of locking affects performance, as thread wait for each other. You have to analyse the workflow to determine what really needs to be locked, when, with what type of lock (simple lock or maybe a ReaderWriterLockSlim). There are many typical ways to prevent deadlock.

    For example when using ReaderWriterLockSlim you can use a timeout to prevent deadlocks (if you wait to much, you abort aquiring the lock)

    if (cacheLock.TryEnterWriteLock(timeout))
    {
    ...
    }
    

    And you should be able to suggest such timeouts.

    At such a question I would expect at least a mention of the classic case of deadlocks, like badly use of nested locks (you should be able to know can you avoid them, why they are bad, etc.).

    The subject is very big... you can go on and on about this. But without definitions. Knowing what a lock is and knowing to use locks/semaphores/mutex in large scale multi-threading applications are 2 different things.