David Rosenblum
David Rosenblum

Reputation: 27

Is a reference parameter in a static method in a static class in C# .NET thread-safe?

Please consider the following class/method being called from a Blazor page instance class. My question is: if two threads call the MyStaticMethod concurrently passing the same ref int index reference as argument, is it possible that the index will not be incremented twice?

public static class MyStaticClass
{
  public static MyClass1 MyStaticMethod(ref int index, string paramValue1,
      MyClass2[]? paramValues2, int paramValue3)
  {
    MyClass1 result = new { Prop1 = paramValue1,
        Prop2 = paramValues2.SomeIntegerValue, Prop3 = paramValue3 };
    index++;
    return result;
  }
}

Upvotes: -1

Views: 75

Answers (1)

Theodor Zoulias
Theodor Zoulias

Reputation: 43845

If two threads call the MyStaticMethod concurrently passing the same ref int index reference as argument, then both threads will interact with the same memory location. The ++ operator is not atomic, so it's entirely possible that one of the two increments will be lost, i.e. the index will be incremented only once. In other words interacting with a shared memory location through a ref variable does not provide a thread-safe environment for the interaction. You still have to deal with the usual implications of the concurrent multithreaded access, by using the lock statement, the Interlocked.Increment method, or other synchronization mechanism.

Upvotes: 0

Related Questions