Nexo
Nexo

Reputation: 2321

Avoid or mitigate race condition for two functions sharing same variable (resource) in C#

Function updating value

protected void updateValue(SomeClassType val){
  // Based upon some condition value for variable is updated
  if(val.id){ // some condition
    counter=2;
  }
}

Function using value

protected void useValue(var counter){
  // Do something with variable.
}

What I Tried

public static AutoResetEvent autoResetEventForUpdateValue = new AutoResetEvent(false);
protected void updateValue(SomeClassType val){
  // Based upon some condition value for variable is updated
  if(val.id){ // some condition
    counter=2;
  }
  autoResetEventForUpdateValue.Set();
}

Function using value

WaitHandle[] waitHandles = new WaitHandle[] { autoResetEventForUpdateValue};
protected void useValue(var counter){
  // Do something with variable.
}

Also updateValue(val), this parameter val of type SomeClassType is not accessible in implementation of class useValue(counter).

Upvotes: 0

Views: 233

Answers (1)

JonasH
JonasH

Reputation: 36341

I would just change UpdateValue to return the value instead of updating it in place, that should make ordering trivial:

var currentCounterValue = ...
var updatedCounterValue = await Task.Run(() => ComputeNewCounterValue(currentCounterValue));
UseValue(updatedCounterValue );

Pure methods, i.e. methods without side effects, where the result only depend on the input, tend to be the easiest to use. This is especially true when dealing with multi threading.

You might also want some mechanism to ensure your method cannot run concurrently. If this is triggered by a button press you could disable the button before you call ComputeNewCounterValue and enable it after UseValue;

Upvotes: 1

Related Questions