K
kirk
I have a class with a custom event that starts a timer when it's
holding subscriptions and stops the timer otherwise. The timer
repeatedly calls an API which takes a string. For each call the
return value of the API is compared against the last obtained value
from it and if different, I fire my custom event. The string that
the API is using for its input arg is defined by a public property to
this class. My question is, how can I guarantee some level of
atomicity and consistency in the timer function when changes are made
to the string used by the API from the caller? Is there a best
practice, maybe there's a better way to rearchitect this entirely?
// sample code
public class TrackChanges
{
private string LastValue = null;
private string CurrValue = null;
private string szThingToTrack = null;
public string ThingToTrack
{
get { return this.szThingToTrack; }
set { this.szThingToTrack = value; }
}
private void TimerFunction
{
if(this.ThingToTrack == null || this.ChangeOccurred == null)
{ return; }
CurrValue = SomeFunction(this.ThingToTrack);
if(this.CurrValue != this.LastValue)
{
this.LastValue = this.CurrValue;
this.ChangeOccurred(this, EventArgs.Empty);
}
}
public event EventHandler ChangeOccurred
{
add... // Timer.Enabled = true
remove... // Timer.Disabled = false if no other subscriptions
}
}
holding subscriptions and stops the timer otherwise. The timer
repeatedly calls an API which takes a string. For each call the
return value of the API is compared against the last obtained value
from it and if different, I fire my custom event. The string that
the API is using for its input arg is defined by a public property to
this class. My question is, how can I guarantee some level of
atomicity and consistency in the timer function when changes are made
to the string used by the API from the caller? Is there a best
practice, maybe there's a better way to rearchitect this entirely?
// sample code
public class TrackChanges
{
private string LastValue = null;
private string CurrValue = null;
private string szThingToTrack = null;
public string ThingToTrack
{
get { return this.szThingToTrack; }
set { this.szThingToTrack = value; }
}
private void TimerFunction
{
if(this.ThingToTrack == null || this.ChangeOccurred == null)
{ return; }
CurrValue = SomeFunction(this.ThingToTrack);
if(this.CurrValue != this.LastValue)
{
this.LastValue = this.CurrValue;
this.ChangeOccurred(this, EventArgs.Empty);
}
}
public event EventHandler ChangeOccurred
{
add... // Timer.Enabled = true
remove... // Timer.Disabled = false if no other subscriptions
}
}