473,586 Members | 2,792 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to guarantee atomicity with state management in a timer

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.szThingToT rack; }
set { this.szThingToT rack = value; }
}

private void TimerFunction
{
if(this.ThingTo Track == null || this.ChangeOccu rred == null)
{ return; }

CurrValue = SomeFunction(th is.ThingToTrack );
if(this.CurrVal ue != this.LastValue)
{
this.LastValue = this.CurrValue;
this.ChangeOccu rred(this, EventArgs.Empty );
}
}

public event EventHandler ChangeOccurred
{
add... // Timer.Enabled = true
remove... // Timer.Disabled = false if no other subscriptions
}
}
Jun 27 '08 #1
3 1252
On Sat, 07 Jun 2008 15:49:28 -0700, kirk <ki****@gmail.c omwrote:
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?
If I understand the question correctly, you are asking how to ensure that
some code trying to change the ThingToTrack property won't interfere with
the operation of the TimerFunction. Of particular concern might be the
value of ThingToTrack changing from the time you compare it to null and
the time you call SomeFunction() (other than that, I don't see a
problem...you have an inherent race condition, but not one that seems
harmful to me, and it's not one you can fix in any case :) ).

I think the simplest solution is the same as the one you _should_ have
applied to the event handler as well. I would change your TimerFunction
method to look like this:

private void TimerFunction()
{
string strTrack = ThingToTrack;
EventHandler handler = ChangeOccurred;

if(strTrack == null || handler == null)
{
return;
}

CurrValue = SomeFunction(st rTrack);
if(this.CurrVal ue != this.LastValue)
{
this.LastValue = this.CurrValue;
handler(this, EventArgs.Empty );
}
}

Both the String and Delegate class are immutable, so once you grab the
reference of the current instance, you can be assured that that instance
won't change. Some other thread could in fact change the original source
from which you got the instance to point to a different reference, but
that won't affect your own code, as long as you fix it to look like the
above.

Note that the above code is still susceptible to other code that tries to
change both the ThingToTrack property and the ChangeOccurred event
simultaneously. Based on what you've written, I don't think that should
be a problem. That is, no other code should assume that it can do that.
But if that's part of your design then yes, you'll need something more
elaborate.

Pete
Jun 27 '08 #2
On Jun 7, 4:04*pm, "Peter Duniho" <NpOeStPe...@nn owslpianmk.com>
wrote:
On Sat, 07 Jun 2008 15:49:28 -0700, kirk <kir...@gmail.c omwrote:
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?

If I understand the question correctly, you are asking how to ensure that *
some code trying to change the ThingToTrack property won't interfere with *
the operation of the TimerFunction. *Of particular concern might be the *
value of ThingToTrack changing from the time you compare it to null and *
the time you call SomeFunction() (other than that, I don't see a *
problem...you have an inherent race condition, but not one that seems *
harmful to me, and it's not one you can fix in any case :) ).

I think the simplest solution is the same as the one you _should_ have *
applied to the event handler as well. *I would change your TimerFunction*
method to look like this:

* * private void TimerFunction()
* * {
* * * *string strTrack = ThingToTrack;
* * * *EventHandler handler = ChangeOccurred;

* * * *if(strTrack == null || handler == null)
* * * *{
* * * * * return;
* * * *}

* * * *CurrValue = SomeFunction(st rTrack);
* * * *if(this.CurrVa lue != this.LastValue)
* * * *{
* * * * * this.LastValue = this.CurrValue;
* * * * * handler(this, EventArgs.Empty );
* * * *}
* * }

Both the String and Delegate class are immutable, so once you grab the *
reference of the current instance, you can be assured that that instance *
won't change. *Some other thread could in fact change the original source *
*from which you got the instance to point to a different reference, but *
that won't affect your own code, as long as you fix it to look like the *
above.

Note that the above code is still susceptible to other code that tries to *
change both the ThingToTrack property and the ChangeOccurred event *
simultaneously. *Based on what you've written, I don't think that should*
be a problem. *That is, no other code should assume that it can do that.*
But if that's part of your design then yes, you'll need something more *
elaborate.

Pete
Thanks Pete. Good suggestions that I am going to put to use. Other
things I am thinking of to strengthen this are; resetting LastValue to
null if ThingToTrack changes to avoid tracking changes between the old
ThingToTrack and the new ThingToTrack (and) what happens if all event
subscriptions have been pulled somewhere in the middle of
TimerFunction when handler gets called, probably a good idea to wrap
that in a Try/Catch { // do nothing } clause.
Jun 27 '08 #3
On Sat, 07 Jun 2008 16:47:01 -0700, kirk <ki****@gmail.c omwrote:
Thanks Pete. Good suggestions that I am going to put to use. Other
things I am thinking of to strengthen this are; resetting LastValue to
null if ThingToTrack changes to avoid tracking changes between the old
ThingToTrack and the new ThingToTrack
Good idea. :)
(and) what happens if all event
subscriptions have been pulled somewhere in the middle of
TimerFunction when handler gets called, probably a good idea to wrap
that in a Try/Catch { // do nothing } clause.
Not an issue. That's why the code I posted copies the delegate to a local
variable before using it. Once that happens, other threads can try to
unsubscribe without affecting the handler. The subscribed delegates will
still get called, but there's little you could do to prevent that anyway.
Even if you synchronized the code, the event-raising code could get the
lock before the unsubscribing code, and the unsubscribing code would have
to deal with allowing the event to be raised anyway.

Yes, this means that the code unsubscribing cannot count on its
unsubscribing code guaranteeing that the previously-subscribed handler
won't be called, but that was true anyway. It's best for the code to not
have to rely on that at all.

Pete
Jun 27 '08 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

14
2663
by: David B. Held | last post by:
I wanted to post this proposal on c.l.c++.m, but my news server apparently does not support that group any more. I propose a new class of exception safety known as the "smart guarantee". Essentially, the smart guarantee promises to clean up resources whose ownership is passed into the function, for whatever defintion of "clean up" is most...
1
3286
by: Paul Tomlinson | last post by:
Question about a System.Threading.Timer object and the "state" object you pass to it... Timer stateTimer = new Timer( = new TimerCallback( OnTimer ), o, 1000, 1000); I have an array of timer objects which all fire into my OnTimer( object state ) function very nicely. I pass in an object "o" on creation of this timer which I subsequently...
4
3991
by: John Q. Smith | last post by:
I'm trying to find out some of the details behind OOP state management with SQL Server. For instance - how long does the session object live on any server? Is it created and destoyed with each page request? - will each reading of a session variable cause a round trip to the DB server? or does the complete session live within the HttpContext...
2
1421
by: geodev | last post by:
Hello, I’m currently writing an asp.net application that will be running on a Windows XP Professional workstation utilising IIS and MSDE Database. At a later date this application will need to run on a Windows Server 2003 IIS web farm utilising either MSDE Database or SQL Server Database. I’m developing this application utilising...
13
2434
by: James Hunter Ross | last post by:
We love the ASP.NET "Session" concept and make good use of it. But, getting close to deployment we find we lose sessions far too often, probably due to application restarts, etc. We hope to eliminate these restarts, but we're not sure that can be achieved. (We are exploring who/what might be touching web.config or assemblies or other files...
5
3831
by: David Lozzi | last post by:
Howdy, is the Session_End event a guarantee event to be fired? I have this memory of back in ASP and IIS 4 that the event was guaranteed, like a 50/50 chance. If I have some shopping cart clean up functions in the Session_End event, will that fire every single time a user's session expires whether from closing the browser window, browsing...
3
2776
by: shahoo | last post by:
Hi, I want to simulate the two buttons in a scroll bar, i.e, use two buttons and when the user clicks on them and holds the button, I should scroll. My problem is when the button is clicked, It scrolls once not for the time the button is down. Can anyone help me with that please?
0
1070
by: kirk | last post by:
I have three events that I have created and manage with timers. Two of the timer event handlers, the last two in the code below, need to reset state management data, if the first event handler fires. My question, is what I have implemented the right way to design state management, or is there maybe a best practice to design this...
0
7908
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7836
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8199
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8336
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
8212
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6606
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
3863
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2343
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
1175
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.