Timer question

B

Benjamin

Hi,
I am having a problem enabling a timer in my class. I have attached some
sample pseudo code (see "Sample code illustrating issue") so you can see
what I am talking about.

Whats the issue?
================
I am unable to pause the timer when a timed event is thrown due to my
event handling having a private scope. If I make the scope public all
works as expected.

I want to keep the scope private as I do not want this routine to be
accessible externally. I also think that I should be able to access this
as an object reference (ie object source) is provided.

How would I go about doing this? If I step into the code I see that
object source is of type System.Timers.Timer and that this is a
reference to my timer. I assume that I need to do some sort of late
binding to access it? How would I do this?

Sample code illustrating issue.
===============================
public class foo{
private System.Timers.Timer CamTimer = new System.Timers.Timer();

public foo()
{
// Initialization
CamTimer.Enabled = false;
CamTimer.Elapsed+=new ElapsedEventHandler(OnTimedEvent);
CamTimer.Interval = interval;
CamTimer.Enabled = true;
CamTimer.Start();
}

private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
// Pause timer
// This is what is failing
CamTimer.Enabled = false

// Do some stuff

// Restart timer
}
}

Many thanks in advance for looking at this.

Regards

Benjamin
 
J

Jon Skeet [C# MVP]

Benjamin said:
I am having a problem enabling a timer in my class. I have attached some
sample pseudo code (see "Sample code illustrating issue") so you can see
what I am talking about.

Whats the issue?
================
I am unable to pause the timer when a timed event is thrown due to my
event handling having a private scope. If I make the scope public all
works as expected.

I want to keep the scope private as I do not want this routine to be
accessible externally. I also think that I should be able to access this
as an object reference (ie object source) is provided.

How would I go about doing this? If I step into the code I see that
object source is of type System.Timers.Timer and that this is a
reference to my timer. I assume that I need to do some sort of late
binding to access it? How would I do this?

Your OnTimedEvent method is static, whereas the variable is an instance
variable. That's the problem.
 
B

Benjamin

Jon said:
Your OnTimedEvent method is static, whereas the variable is an instance
variable. That's the problem.

Thank you for such a quick response. You were quite correct. Looks like
I need to do some more reading...

Thanks again, much appreciated.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top