Static Function Concurrency ASP.NET

后端 未结 7 1376
遇见更好的自我
遇见更好的自我 2021-02-09 19:14

If you have two threads invoking a static function at the same moment in time, is there a concurrency risk? And if that function uses a static member of the class, is there even

7条回答
  •  走了就别回头了
    2021-02-09 19:53

    Yes, there is a concurrency risk when you modify a static variable in static methods.

    The static functions themselves have distinct sets of local variables, but any static variables are shared.

    In your specific samples you're not being exposed, but that's just because you're using constants (and assigning the same values to them). Change the code sample slightly and you'll be exposed.

    Edit:

    If you call both Sum1() AND Sum2() from different threads you're in trouble, there's no way to guarantee the value of a and b in this statement: int c = a + b;

    private static int a = 5;
    
    public static int Sum1()
    {
        int b = 4;
        a = 9;
        int c = a + b;
        return c;
    }
    
    public static int Sum2()
    {
       int b = 4;
       int c = a + b;
       return c;
    }
    

    You can also achieve concurrency problems with multiple invocations of a single method like this:

    public static int Sum3(int currentA)
    {
       a = currentA;
       int b = 4;
       int c = a + b;
       int d = a * b; // a may have changed here
       return c + d;
    }
    

    The issue here is that the value of a may change mid-method due to other invocations changing it.

提交回复
热议问题