Simple C# Interlocked use case

Original code in a ViewModel for a Windows Phone application looked like this:

 private readonly object _lock = new object();
 private int _secondsToNextRefresh;
 public int SecondsToNextRefresh
 {
 get { return _secondsToNextRefresh; }
 set { _secondsToNextRefresh = value; RaisePropertyChanged(() => SecondsToNextRefresh); }
 }

 protected void ResetRefreshTimer()
 {
 if (_refreshTimer == null)
 {
  _refreshTimer = new Timer(arg =>
  {
    if (SecondsToNextRefresh == 0)
    {     
     GetData();
     SecondsToNextRefresh = GetSecondsToNextRefresh();
    }
    else
    { 
     ModifySecondsToNextRefresh(SecondsToNextRefresh - RefreshPeriodInSec);
    }
    },null, 0, RefreshPeriodInSec * Constants.MilliSecsPerSec);
  } 
 }

protected int ModifySecondsToNextRefresh(int value)
 { 
   lock (_lock)
  {
   SecondsToNextRefresh = value; 
  }
  return SecondsToNextRefresh;
}

Upon further inspection of the code, it appeared to me that I can take advantage of the higher performance C# Interlocked methods.

Changing the above code to:


_refreshTimer = new Timer(arg =>
{
 if (_secondsToNextRefresh == 0)
 {   
   secsToNextRefresh = GetSecondsToNextRefresh();
   GetData(); 
  }
  ModifySecondsToNextRefresh(secsToNextRefresh) 

},null, 0, RefreshPeriodInSec * Constants.MilliSecsPerSec);

protected int ModifySecondsToNextRefresh(int value)
{ 
  var valueToReturn = Interlocked.Exchange(ref _secondsToNextRefresh, value);
  RaisePropertyChanged(() => SecondsToNextRefresh);
  return valueToReturn;
}

Based on advise from Writing High Performance .NET Code, surely is the preferred locking mechanism in this scenario.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s