473,725 Members | 2,126 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

static timers

I need some insight into timers, the static modifier and instance memory
safety.
public class myClass
{
protected static int i = 0;
portected float myfloat;
protected static Timer staticTimer = new Timer();
}

public class myObject: myClass
{
public myClass()
{
staticTimer.Ela psed+=ElapsedEv entHandler(this .onStaticTimerE vent);
staticTimer.Int erval = 999;
staticTimer.ena bled = true;
}
private void onStaticTimerEv ent( ...)
{
lock(i)
{
i++;
myFLoat +=i;
}
}
}

Assume I create 100 instances of myObject. I assume there is only one
staticTimer. So how do the 100 instances interact with only one timer
instance? And do I need the lock on (i) - I would assume that since there is
only one timer, onStaticTimerEv ent (specificlly i) would be thread safe from
other instances.

Is it practice to have the timer declared and instantiated within the
instance? In this case, one hundred staticTimers would exist and the lock(i)
would be needed.
May 23 '06 #1
7 5688
Hi,

"FredC" <Fr***@discussi ons.microsoft.c om> wrote in message
news:B5******** *************** ***********@mic rosoft.com...
I need some insight into timers, the static modifier and instance memory
safety.
Why are they static in the first place?
Assume I create 100 instances of myObject. I assume there is only one
staticTimer.
YES, and you will reset it each time you create a new instance
So how do the 100 instances interact with only one timer
instance? And do I need the lock on (i) - I would assume that since there
is
only one timer, onStaticTimerEv ent (specificlly i) would be thread safe
from
other instances.
yes, you will eventually have a lot of waiting, everybody will be waiting
for i to unlock

Is it practice to have the timer declared and instantiated within the
instance? In this case, one hundred staticTimers would exist and the
lock(i)
would be needed.

What is what you want to do? The current solution is FAR from perfect.

--
--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation
May 23 '06 #2
Hello FredC,

Firstly, take into account register/unregister events are thread-safe if
its called from outside the class with the event.
If u call it within the class you must provide thread safety yourself by
calling += or -= within a lock statement.

Secondly, int is an atom statement, for most cases you shouldn't syncronize
it

F> I need some insight into timers, the static modifier and instance
F> memory
F> safety.
F> public class myClass
F> {
F> protected static int i = 0;
F> portected float myfloat;
F> protected static Timer staticTimer = new Timer();
F> }
F> public class myObject: myClass
F> {
F> public myClass()
F> {
F>
F> staticTimer.Ela psed+=ElapsedEv entHandler(this .onStaticTimerE vent);
F> staticTimer.Int erval = 999;
F> staticTimer.ena bled = true;
F> }
F> private void onStaticTimerEv ent( ...)
F> {
F> lock(i)
F> {
F> i++;
F> myFLoat +=i;
F> }
F> }
F> }
F> Assume I create 100 instances of myObject. I assume there is only one
F> staticTimer. So how do the 100 instances interact with only one timer
F> instance? And do I need the lock on (i) - I would assume that since
F> there is only one timer, onStaticTimerEv ent (specificlly i) would be
F> thread safe from other instances.
F>
F> Is it practice to have the timer declared and instantiated within the
F> instance? In this case, one hundred staticTimers would exist and the
F> lock(i) would be needed.
F>
---
WBR,
Michael Nemtsev :: blog: http://spaces.msn.com/laflour

"At times one remains faithful to a cause only because its opponents do not
cease to be insipid." (c) Friedrich Nietzsche
May 23 '06 #3
FredC,

See inline:
Assume I create 100 instances of myObject. I assume there is only one
staticTimer. So how do the 100 instances interact with only one timer
instance? And do I need the lock on (i) - I would assume that since there
is
only one timer, onStaticTimerEv ent (specificlly i) would be thread safe
from
other instances.
The first thing that strikes me as odd is that you have a method named
myClass in your class. I think you meant myObject, and you meant to have it
be the constructor.

You would also be setting the interval for the timer every time you
create a class. Generally speaking, you should do this once, maybe in the
static constructor of the type that has a reference to the timer.

On top of that, you will probably get an exception somewhere along the
line. The reason for this is that you are boxing the int i before you pass
it to the lock. When you exit the lock, the boxed instance is different,
and you are trying to exit a block with a different object reference (one
that hasn't been locked on).

Finally, every instance of this class that you create is never going to
be garbage collected. The reason for this is that the class registers the
event handler with the static timer, which keeps the reference alive as long
as the timer is alive. Because it is static, it will shut down when the app
shuts down.

Needless to say, this is not optimal.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

Is it practice to have the timer declared and instantiated within the
instance? In this case, one hundred staticTimers would exist and the
lock(i)
would be needed.

May 23 '06 #4
FredC,

This code won't produce the result you probably expect.

Your timer variable is static, but you create the timer and assigned the
variable in the instance constructor. That means every new instance of my
class will create new timer and will assigned to the static variable thus
overriding the old reference. As long as there is no reference to the old
timer anymore it will eventually finalized and garbage collected. Upon
finalization the timer will be disabled, but until that you are going to
receive ticks from it.

If you fix the problem I just explained to you and since the event handler
is instance method each MyClass object will receive notification from the
timer. The event handler will be executed one by one from the same thread
pool thread. That means if the timer event is the only one that is modifying
this variable you are safe. Depending on the time needed to process the
event and the number of event handlers the timer might appear to be not
accurate enough.

--
HTH
Stoitcho Goutsev (100)

"FredC" <Fr***@discussi ons.microsoft.c om> wrote in message
news:B5******** *************** ***********@mic rosoft.com...
I need some insight into timers, the static modifier and instance memory
safety.
public class myClass
{
protected static int i = 0;
portected float myfloat;
protected static Timer staticTimer = new Timer();
}

public class myObject: myClass
{
public myClass()
{
staticTimer.Ela psed+=ElapsedEv entHandler(this .onStaticTimerE vent);
staticTimer.Int erval = 999;
staticTimer.ena bled = true;
}
private void onStaticTimerEv ent( ...)
{
lock(i)
{
i++;
myFLoat +=i;
}
}
}

Assume I create 100 instances of myObject. I assume there is only one
staticTimer. So how do the 100 instances interact with only one timer
instance? And do I need the lock on (i) - I would assume that since there
is
only one timer, onStaticTimerEv ent (specificlly i) would be thread safe
from
other instances.

Is it practice to have the timer declared and instantiated within the
instance? In this case, one hundred staticTimers would exist and the
lock(i)
would be needed.

May 23 '06 #5
Where do you see that it will create a new instance of the timer every
time myObject is created? It will be created once, the first time the type
is accessed.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"Stoitcho Goutsev (100)" <10*@100.com> wrote in message
news:e2******** ******@TK2MSFTN GP03.phx.gbl...
FredC,

This code won't produce the result you probably expect.

Your timer variable is static, but you create the timer and assigned the
variable in the instance constructor. That means every new instance of my
class will create new timer and will assigned to the static variable thus
overriding the old reference. As long as there is no reference to the old
timer anymore it will eventually finalized and garbage collected. Upon
finalization the timer will be disabled, but until that you are going to
receive ticks from it.

If you fix the problem I just explained to you and since the event handler
is instance method each MyClass object will receive notification from the
timer. The event handler will be executed one by one from the same thread
pool thread. That means if the timer event is the only one that is
modifying this variable you are safe. Depending on the time needed to
process the event and the number of event handlers the timer might appear
to be not accurate enough.

--
HTH
Stoitcho Goutsev (100)

"FredC" <Fr***@discussi ons.microsoft.c om> wrote in message
news:B5******** *************** ***********@mic rosoft.com...
I need some insight into timers, the static modifier and instance memory
safety.
public class myClass
{
protected static int i = 0;
portected float myfloat;
protected static Timer staticTimer = new Timer();
}

public class myObject: myClass
{
public myClass()
{
staticTimer.Ela psed+=ElapsedEv entHandler(this .onStaticTimerE vent);
staticTimer.Int erval = 999;
staticTimer.ena bled = true;
}
private void onStaticTimerEv ent( ...)
{
lock(i)
{
i++;
myFLoat +=i;
}
}
}

Assume I create 100 instances of myObject. I assume there is only one
staticTimer. So how do the 100 instances interact with only one timer
instance? And do I need the lock on (i) - I would assume that since
there is
only one timer, onStaticTimerEv ent (specificlly i) would be thread safe
from
other instances.

Is it practice to have the timer declared and instantiated within the
instance? In this case, one hundred staticTimers would exist and the
lock(i)
would be needed.


May 23 '06 #6
FredC wrote:
I need some insight into timers, the static modifier and instance memory
safety.
public class myClass
{
protected static int i = 0;
portected float myfloat;
protected static Timer staticTimer = new Timer();
}

public class myObject: myClass
{
public myClass()
{
staticTimer.Ela psed+=ElapsedEv entHandler(this .onStaticTimerE vent);
staticTimer.Int erval = 999;
staticTimer.ena bled = true;
}
private void onStaticTimerEv ent( ...)
{
lock(i)
{
i++;
myFLoat +=i;
}
}
}

Assume I create 100 instances of myObject. I assume there is only one
staticTimer. So how do the 100 instances interact with only one timer
instance?
Yes, there is only one Timer object. The event handlers will each be
started using a separate thread. As they all start at once, the system
might get quite sluggish when they do.

You might want to limit the number of handlers per timer, or fire the
timer more often and use a dispatcher to call the handlers on a rotating
scheme.
And do I need the lock on (i) - I would assume that since there is
only one timer, onStaticTimerEv ent (specificlly i) would be thread safe from
other instances.
No, the timer starts the delegate in a new thread.

A lock on the variable i is totally worthless, though. What you actually
will be doing is copying the value of the variable and box it inside a
new object on the heap, and perform the lock on that object. As each
thread would create a new object to do the lock on, the locking has no
effect what so ever. You have to use a reference type variable for the
locking.
Is it practice to have the timer declared and instantiated within the
instance? In this case, one hundred staticTimers would exist and the lock(i)
would be needed.


If you want to use a static timer, add a proper static constructor to
the class where you initialize the timer.

A lock will be needed regardless if you have one or a hundred timers.
May 23 '06 #7
Oops, I'm sorry.
Just ignore my fitst comment. I thought I saw 'new Timer()' in the instnace
constructor. I was wrong.
--

Stoitcho Goutsev (100)

"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard .caspershouse.c om> wrote in
message news:ek******** ******@TK2MSFTN GP05.phx.gbl...
Where do you see that it will create a new instance of the timer every
time myObject is created? It will be created once, the first time the
type is accessed.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"Stoitcho Goutsev (100)" <10*@100.com> wrote in message
news:e2******** ******@TK2MSFTN GP03.phx.gbl...
FredC,

This code won't produce the result you probably expect.

Your timer variable is static, but you create the timer and assigned the
variable in the instance constructor. That means every new instance of my
class will create new timer and will assigned to the static variable thus
overriding the old reference. As long as there is no reference to the old
timer anymore it will eventually finalized and garbage collected. Upon
finalization the timer will be disabled, but until that you are going to
receive ticks from it.

If you fix the problem I just explained to you and since the event
handler is instance method each MyClass object will receive notification
from the timer. The event handler will be executed one by one from the
same thread pool thread. That means if the timer event is the only one
that is modifying this variable you are safe. Depending on the time
needed to process the event and the number of event handlers the timer
might appear to be not accurate enough.

--
HTH
Stoitcho Goutsev (100)

"FredC" <Fr***@discussi ons.microsoft.c om> wrote in message
news:B5******** *************** ***********@mic rosoft.com...
I need some insight into timers, the static modifier and instance memory
safety.
public class myClass
{
protected static int i = 0;
portected float myfloat;
protected static Timer staticTimer = new Timer();
}

public class myObject: myClass
{
public myClass()
{

staticTimer.Ela psed+=ElapsedEv entHandler(this .onStaticTimerE vent);
staticTimer.Int erval = 999;
staticTimer.ena bled = true;
}
private void onStaticTimerEv ent( ...)
{
lock(i)
{
i++;
myFLoat +=i;
}
}
}

Assume I create 100 instances of myObject. I assume there is only one
staticTimer. So how do the 100 instances interact with only one timer
instance? And do I need the lock on (i) - I would assume that since
there is
only one timer, onStaticTimerEv ent (specificlly i) would be thread safe
from
other instances.

Is it practice to have the timer declared and instantiated within the
instance? In this case, one hundred staticTimers would exist and the
lock(i)
would be needed.



May 23 '06 #8

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

Similar topics

3
2037
by: Jeff Greenland | last post by:
Hello everyone, I am having problems with Timers in a web application. They just seem to stop running after 15 minutes or so. My web application is set up like this: When a user hits a page in the site, that page (.aspx) instantiates a compiled class (.DLL). The instantiation process creates a Timer that runs in the background to perform tasks every so often (such as notifying clients
9
7875
by: Mark Rae | last post by:
Hi, I've seen several articles about using System Timers in ASP.NET solutions, specifically setting them up in Global.asax' Application_OnStart event. I'm thinking about the scenario where I might need to carry out some back-end processing without pausing the individual users' Session while that process runs. E.g. I might provide the ability for a user to upload a text file of job
10
2706
by: WhiteSocksGuy | last post by:
Help! I am new to Visual Basic .Net (version 2002) and I am trying to get a System.Timers.Timer to work for me to display a splash screen for about two seconds and then load the main form. I have two forms (frmSplash and frmMain) and a code Module setup as my startup object. Here is the code that I have, when I try to run this part of the splash screen form shows and then program terminates. What am I doing wrong? Thanks,
6
15061
by: Gene Hubert | last post by:
I seem to be getting crazy results when I have multiple System.Windows.Forms.Timer objects in the same form running at the same time. When only one timer is running I get the expected behavior. When I have two timers running at once, one fires reliably and the other fires almost never. Are there any known issues with this? Thanks, Gene H.
1
1902
by: Bamse | last post by:
Hi, can timers be used in webservices? as an example: to check at some time interval an object - Application and for each logged user, check its login period, and if it is greater than 30 minutes, remove it form the collection. Thank you, Daniel
5
9887
by: Michael C# | last post by:
Hi all, I set up a System.Timers.Time in my app. The code basically just updates the screen, but since the processing performed is so CPU-intensive, I wanted to make sure it gets updated regularly; like every 1.5 secs. or so. I only ran into one issue - the MyTimer_Elapsed event handler was not updating the screen correctly all the time, often leaving large chunks of the screen un-painted for several seconds. On a whim I decided to...
9
1358
by: N! Xau | last post by:
hi I need a way to threat a certain number of timers in a homogeneous way. Let's say I have this code: select X case 1 timer1.enabled = true case 2
1
1827
by: | last post by:
Frustrated.. (I have seen other posts regarding this problem with no resolution..) I am using dotnet 1.1 with latest SP on a Win2KP box (actually 2 boxes), have even run the service on WinXP SP2 box.. I have created a service to grab data off a receive socket (small packets), place in a queue (Queue class), and do an insert into SQL. I have 3 timers in my project. One checks the status of the sql service every 15 seconds, one checks the...
1
3049
by: Jonathan Woods | last post by:
Hi there, I have three methods these need to execute at every interval time. I would like to know which option is better? Option A) Three System.Timers.Timer objects these execute each method. timer1.Elapsed += new System.Timers.ElapsedEventHandler(Method1_Elapsed);
0
8888
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 usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9257
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9113
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8097
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6702
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4784
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3221
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
2
2635
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2157
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.