-1

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;
  }
}
2
  • 4
    It depends how you are calling it Commented Feb 26 at 18:26
  • I am voting to reopen this question because although the linked question has a very similar title, its body is convoluted, verbose, and not relevant to the integer increment that is asked here. Commented Feb 27 at 15:23

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.