C#/.Net Analysis Tool to Find Race Conditions/Deadlocks

C#/.NET analysis tool to find race conditions/deadlocks

You're probably looking for one of these:

  • CHESS
  • Typemock Racer

NOTE: This answer is from 2010. As with all recommendations answers, recommendations tend to change over time. There may be other products out there now, CHESS which was a Microsoft Research Labs project may have evolved into a final product or been scrapped altogether. Please take this answer with a grain of salt and conduct new research into which products are suitable now.

Unit Testing, Deadlocks, and Race Conditions

Take a look at TypeMock Racer (it's in Beta)

edit: actually Alpha

http://www.typemock.com/Typemock_software_development_tools.html

How to find out deadlock and prevent it in C#

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.

Detecting deadlocks in a C# application

Instead of using the regular lock & Monitor.Enter approach to lock some data, you can also use a 'TimedLock' structure.
This TimedLock throws an exception if the lock couldn't be acquired in a timely fashion, and it can also give you a warning if you have some locks that you didn't release.

This article by Ian Griffiths could maybe help.

Looking for a Static Code Analysis Tool For Concurrency in .NET like CheckThread for java

Here are a set of resources to help with concurrent programming...they are a mixture of static and runtime based tools.

Intel Inspector XE/Parallel Studio

Intel do some tools inside Parallel Studio that help with concurrent development, however their Parallel Advisor is only for C/C++.

But for C# you can do runtime thread checking with their Inspector XE (formerly Intel Thread Checker)

  • http://software.intel.com/en-us/articles/intel-inspector-xe/.

PRESharp (Microsoft Center for Software Excellence)

There appears to be something called PRESharp mentioned here:

  • http://www.microsoft.com/windows/cse/pa_projects.mspx

Now I haven't heard of that before...only the similar sounding PREFast which I have used to statically analyse some C driver code in the past. I suspect that it's an internal Microsoft tool that no one else gets to use unless you get special access.


Static Analysis Tools

A big list of static analysis tools here (e.g. FXCop).

  • What static analysis tools are available for C#?

and Typemock Racer mentioned here:

  • C#/.NET analysis tool to find race conditions/deadlocks

and of note is Coverity Prevent which claims to detect concurrency defects by statically analysing C/C++, Java or C# code (rated by NASA).

  • http://www.verifysoft.com/en_coverity_prevent_concurrency.html

  • http://www.theregister.co.uk/2012/08/22/mars_rover_software_coverity/)


WinDBG + SOSEX

Other tools to help with concurrent programming are WinDBG (part of the Windows Debugging Tools which is distributed inside the Windows SDK) which is more powerful than the Visual Studio debugger.

  • http://msdn.microsoft.com/en-us/windows/hardware/gg463009.aspx

Note: you can now use a more powerful User Mode debugger from inside Visual Studio 2012 which has parity with WinDBG if you install the Windows Driver Kit 8 in your system.

  • http://msdn.microsoft.com/en-us/library/windows/hardware/gg487428.aspx

  • http://blogs.msdn.com/b/mariohewardt/archive/2012/06/05/visual-studio-2012-and-windbg-integration.aspx

You can also get plugins to WinDBG that extend it e.g. the SOSEX plugin adds the !dlk command which can help identify the cause of a deadlock.

  • http://stevestechspot.com/

  • http://blog.scriptico.com/04/debugging-with-windbg-deadlocks-in-applications/

  • Debugging a Deadlock with Windbg's !clrstack command

  • http://blogs.msdn.com/b/tess/archive/2008/02/11/hang-caused-by-gc-xml-deadlock.aspx


Concurrency Visualizer (in Visual Studio 2010+)

There is the Concurrency Visualizer in Visual Studio and an SDK to go with it.

  • http://msdn.microsoft.com/en-us/library/dd537632.aspx

  • http://blogs.msdn.com/b/visualizeparallel/archive/2011/10/17/introducing-the-concurrency-visualizer-sdk.aspx

  • http://msdn.microsoft.com/en-us/magazine/ee336027.aspx

  • http://msdn.microsoft.com/en-us/magazine/ee410778.aspx


General Concurrent Programming Design Considerations

  • http://msdn.microsoft.com/en-us/magazine/cc817398.aspx

  • http://msdn.microsoft.com/en-us/library/ff963553.aspx

  • http://msdn.microsoft.com/en-us/magazine/cc872852.aspx

  • http://msdn.microsoft.com/en-us/magazine/cc163744.aspx

  • http://www.packtpub.com/beginners-guide-for-C-sharp-2008-and-2005-threaded-programming/book


Video Resources

Here's a brilliant series of Videos that give you general advice on debugging .NET applications:

  • http://channel9.msdn.com/Series/-NET-Debugging-Stater-Kit-for-the-Production-Environment/Diagnosing-Application-Issues-01

What static analysis tools are available for C#?

Code violation detection Tools:

  • FxCop, excellent tool by Microsoft. Check compliance with .NET framework guidelines.

    Edit October 2010: No longer available as a standalone download. It is now included in the Windows SDK and after installation can be found in Program Files\Microsoft SDKs\Windows\ [v7.1] \Bin\FXCop\FxCopSetup.exe

    Edit February 2018: This functionality has now been integrated into Visual Studio 2012 and later as Code Analysis

  • Clocksharp, based on code source analysis (to C# 2.0)

  • Mono.Gendarme, similar to FxCop but with an open source licence (based on Mono.Cecil)

  • Smokey, similar to FxCop and Gendarme, based on Mono.Cecil. No longer on development, the main developer works with Gendarme team now.

  • Coverity Prevent™ for C#, commercial product

  • PRQA QA·C#, commercial product

  • PVS-Studio, commercial product

  • CAT.NET, visual studio addin that helps identification of security flaws Edit November 2019: Link is dead.

  • CodeIt.Right

  • Spec#

  • Pex

  • SonarQube, FOSS & Commercial options to support writing cleaner and safer code.

Quality Metric Tools:

  • NDepend, great visual tool. Useful for code metrics, rules, diff, coupling and dependency studies.
  • Nitriq, free, can easily write your own metrics/constraints, nice visualizations. Edit February 2018: download links now dead. Edit June 17, 2019: Links not dead.
  • RSM Squared, based on code source analysis
  • C# Metrics, using a full parse of C#
  • SourceMonitor, an old tool that occasionally gets updates
  • Code Metrics, a Reflector add-in
  • Vil, old tool that doesn't support .NET 2.0. Edit January 2018: Link now dead

Checking Style Tools:

  • StyleCop, Microsoft tool ( run from inside of Visual Studio or integrated into an MSBuild project). Also available as an extension for Visual Studio 2015 and C#6.0
  • Agent Smith, code style validation plugin for ReSharper

Duplication Detection:

  • Simian, based on source code. Works with plenty languages.
  • CloneDR, detects parameterized clones only on language boundaries (also handles many languages other than C#)
  • Clone Detective a Visual Studio plugin (which uses ConQAT internally)
  • Atomiq, based on source code, plenty of languages, cool "wheel" visualization

General Refactoring tools

  • ReSharper - Majorly cool C# code analysis and refactoring features

Unit test for thread safe-ness?

There are two products that can help you there:

  • Microsoft Chess
  • Typemock Racer

Both check for deadlocks in your code (via unit test) and I think Chess checks for race conditions as well.

Using both tools is easy - you write a simple unit test and the run your code several times and check if deadlocks/race conditions is possible in your code.

Edit:
Google has released a tool that checks for race condition in runtime (not during tests) that called thread-race-test.

it won't find all of the race conditions because it only analyse the current run and not all of the possible scenarios like the tool above but it might help you find the race condition once it happens.

Update:
Typemock site no longer had a link to Racer, and it was not been updated in the last 4 years. I guess the project was closed.

Run periodically and asynchronously a function that is thread unsafe in C#

Just start a thread which initializes the camera and runs the capture periodically, until you call Stop camera. Dont forget, NewFrameAvailable runs on the capturing thread, so either create a copy or you could calculate the WaitOne(timeout) on how long the processing took.

You could do something like this:

public class ICameraService
{
public event EventHandler NewFrameAvailable;
public event EventHandler StateChanged;

private ICamera camera;
private Timer frameTimer;
private ManualResetEvent _terminate = new AutoResetEvent(false);
private int interval;

private Thread thread;

public void StartCapture(int interval)
{
_terminate.Reset();
this.interval = interval;
thread = new Thread(ThreadMethod);
}

public void ThreadMethod()
{
StateChanged?.Invoke(this, StateChangedEventArgs("Configuring"));
camera.Configure(...);
StateChanged?.Invoke(this, StateChangedEventArgs("Capturing"));
while(!_terminate.WaitOne(interval))
{
var image = camera.Capture();
image = DoSomeBasicProcessing(image);
NewFrameAvailable?.Invoke(this, NewFrameAvailableEventArgs(image));
}
StateChanged?.Invoke(this, StateChangedEventArgs("Idle"));
}

public void StopCapture()
{
_terminate.Set();
thread.Join();
StateChanged?.Invoke(this, StateChangedEventArgs("Idle"));
}
}


Related Topics



Leave a reply



Submit