Reputation: 647
I have this variable:
private static volatile int _filesInUse;
This variable is accessed via different threads and I want to lock this when it's value is changing in order to update my UI about the current state.
Upvotes: 0
Views: 51
Reputation: 156978
For changing the integer, you have Interlocked.Increment
. You just have to pass it in with the ref
keyword:
int result = Interlocked.Increment(ref _filesInUse);
Use result
along the way (it doesn't get updated when _filesInUse
does, so it is save in your procedure to use it).
Upvotes: 5
Reputation: 759
Why don't you use a [lock][1]
object lockObject = new object();
lock(lockObject)
{
// do your value changing stuff
}
Upvotes: 0
Reputation: 48091
You should provide a method to change that value that is synched:
[MethodImpl(MethodImplOptions.Synchronized)]
public void SomeMethod() {/* code */}
Upvotes: 0