Static Function Concurrency ASP.NET

2019-03-20 12:25发布

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 a bigger problem?

  • Are the two calls seperated from each other? (the function is like copied for the two threads?)
  • Are they automatically queued?

For instance in next example, is there a risk?

private static int a = 5;

public static int Sum()
{
    int b = 4;
    a = 9;
    int c = a + b;
    return c;
}

And next example, is there a risk?

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

Update: And indeed, if both functions are in the same class, what is the risk then?

thx, Lieven Cardoen

7条回答
爷、活的狠高调
2楼-- · 2019-03-20 13:16

In your two examples, there is no thread safety issues because each call to the function will have it's own copy of the local variables on the stack, and in your first example with 'a' being a static variable, you never change 'a', so there is no problem.

If you change the value in 'a' in your first example you will have a potential concurrency problem.

查看更多
登录 后发表回答