Static Function Concurrency ASP.NET

后端 未结 7 1377
遇见更好的自我
遇见更好的自我 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:59

    See here for a discussion on local variables. before your edit neither of the above methods themselves presented a concurrency risk; the local variables are all independent per call; the shared state (static int a) is visible to multiple threads, but you don't mutate it, and you only read it once.

    If you did something like:

    if(a > 5) {
        Console.WriteLine(a + " is greater than 5");
    } // could write "1 is greater than 5"
    

    it would (in theory) not be safe, as the value of a could be changed by another thread - you would typically either synchronize access (via lock etc), or take a snapshot:

    int tmp = a;
    if(tmp > 5) {
       Console.WriteLine(tmp + " is greater than 5");
    }
    

    If you are editing the value, you would almost certainly require synchronization.

提交回复
热议问题