0

I want to increment a int variable and assign it to another int in a atomic operation.

I know about Interlocked.Increment method. But as I understand it can only increment the passed variable atomicly, but not assign the result to a new variable.

So my approach is to lock on a object like this:

private static int globalCounter;
private static object LockObject;
private int localCounter;

/* ... */

lock (LockObject)
{
    globalCounter++;

    localCounter = globalCounter;
}

Is there a more elegant way to do this?

user11909
  • 1,235
  • 11
  • 27

0 Answers0