none
C# increment value and reset as safe thread RRS feed

  • Question

  • is the only way to increment a value and reset it once it reached some value is using lock or there is another way?

    private long value=1;
    private long MAX_VALUE=555555;
    private object obj=new object9);
    
    lock(obj){
    Interlocked.Increment(ref value);
    value= Interlocked.CompareExchange(ref value,1,MAX_VALUE);
    }
    

    Friday, June 21, 2019 9:18 PM

All replies

  • Since it is two operations, you'll need to use a lock.  Within the lock, you don't really need the Interlocked operations.  You could just say

        lock(obj) { value = (value % MAX_VALUE) + 1; }


    Tim Roberts | Driver MVP Emeritus | Providenza & Boekelheide, Inc.

    Saturday, June 22, 2019 12:12 AM