简体   繁体   中英

Are C# Static Extensions Thread Safe?

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

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://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/lock-statement

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM