Thursday, June 14, 2012

A quick and dirty way to diagnose a thread collision problem in c#

If you are having a problem that looks like it might be a rcing condition or other threading type issue, here is a quick and dirty test to determine if it's threading or not. Set up a scenerio that reproduces the error (say running it in several (10) threads in a constant loop overnight) Apply this attribute to your class [Synchronization] That forces all the instances of the class to run on a single thread (way slower). Re run your test. If your problem goes away, you have a threading issue. If speed is a concern, you need to go back and do all the locking around the code that touches that object. If you convert everything to use properties for the objects in question you can just lock the getter and setter. If the quick and dirty test fails to fix the issue, it's probabaly something else. For instance if you're using unsafe code or unsafe dlls (ie stuff written in non .Net c++), it might be a memory corruption problem.

2 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Don't forget your class msut inherit ContextBoundObject
    see this link
    http://msdn.microsoft.com/en-us/library/system.runtime.remoting.contexts.synchronizationattribute.aspx

    ReplyDelete