473,698 Members | 2,751 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 5674
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
2033
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
7868
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
2702
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
15050
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
1901
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
9876
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
1356
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
3044
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
8603
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9157
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9026
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...
1
8893
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7723
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
6518
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
4366
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3045
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
3
2001
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.