0

I'm using a static extension to convert a string to Sha256 as shown below:

    public static string ToSha256(this string value)
    {
        var message = Encoding.ASCII.GetBytes(value);
        SHA256Managed hashString = new SHA256Managed();
        string hex = "";

        var hashValue = hashString.ComputeHash(message);
        foreach (byte x in hashValue)
        {
            hex += String.Format("{0:x2}", x);
        }
        return hex;
    }

Notice the static keyword. What happens when two threads come in concurrently and modifies any of the internal variables in the function, will the outcome be affected?

Thanks

user1034912
  • 2,153
  • 7
  • 38
  • 60
  • 2
    Two threads are not sharing anything; also, `value` is `string` which is immutable. So, no problem. – mshsayem May 27 '18 at 02:07
  • 2
    Only the function is static, not the variables you have declared inside it (in fact, you can't do that in C# to avoid that kind of problem) so while the calls you make to other functions are thread safe, yes, it's thread safe. – Gusman May 27 '18 at 02:08
  • Possible duplicate of [What Makes a Method Thread-safe? What are the rules?](https://stackoverflow.com/questions/9848067/what-makes-a-method-thread-safe-what-are-the-rules) – TheGeneral May 27 '18 at 03:58
  • Go straight to Erics answer, do not pass go – TheGeneral May 27 '18 at 03:59

1 Answers1

0

Static has no bearing when considering code to be thread safe or not. Static only means that the method and it’s data is not replicated across all class instances. You must try to imagine what happens to your code should a second thread enter while the first thread is still busy. Ask yourself what happens to the data in your local variables while you busy working with them.

Suppose thread 1 will enter your method it sets value of string hex to empty on line 3 of your sample. It then proceeds to the for loop. While thread 1 is still in the for loop thread 2 enters and sets hex string value back to empty. Not good sir!

This code is not thread safe. You should simply use the lock keyword against some private static object.

Example here: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/lock-statement

Shaun
  • 11
  • 2