Yesterday I fight with a strange bug, I have a simple class that calculate Sha256 of a string, It was used in a old part of a project where a single thread does a series of operations. Some months later the program is heavily evolved, and there is a new part that uses async pattern to do some operations, since I need to have a Sha256 value I reused the old function called Utils.CalculateSha256.

After some days, some strange thing happened, in application logs I see that sometime there are exception in a routine, I double check the code with Guardian and we could not find the reason for the error. Since the function is executed concurrently by several thread we double check every line for thread safety, but we could not find any error. After some investigation we found that sometime the Sha256 value is wrong for some input string. The error was the following: the function relays on the Utils.CalculateSha256(), this function uses a static SHA256Managed object, and when we check the documentation we found that SHA256Managed object is not thread safe.

Since that function was written when the software does not use it by multiple thread it was considered safe. The rule is, when you do multi thread programming always check for thread safety for every shared object, even for the utility function you use inside the main function thread.

Alk.

Tags:



kick it on DotNetKicks.com

7 Responses to “Always check for objects thread safety when you are doing multi thread programs”

  1. the problem is how to check?

  2. Yes, checking thread safety is really a difficult stuff. If the code is not to complex I find useful to check with other people. Simply explain to others because you want to be multi thread, and try to explain because you are thinking that everything is ok.

    Quite often other people will spot potential problem in your code. Code review is the best way I know to spot difficult to test bug.

    alk.

  3. So how did you solve your problem with SHA256?

  4. Yes yes, the solution was simple, I create a new SHA256Managed each time I called the function, or if you want to avoid creating unnecessary SHA256Managed instance, you can create a static variable and mark with ThreadStaticAttribute
    http://msdn.microsoft.com/en-u.....nd%29.aspx

    Alk.

  5. Great. If only everything multi-thread related was so ’simple’.

    Thank you!

  6. Hi,

    Cricket as we know is currently the second most followed sport after soccer, with many countries now getting in cricket, can cricket overtake soccer as the most followed sports ever?

  7. Greetings! :)

    I just happened to find this community here and I have high hopes of contributing. Really great knowledge here. Exceptional work by the admin, mods and other community members.

    Have a neat Day! http://upload.wikimedia.org/wi.....sSmile.png

Leave a Reply