Alex Alex - 24 days ago 20
C# Question

C# timers.timer

My application looks like this:

I have an MDI parent form - form1, the form that starts and stops the timer - form 2, and a timerCalls class with all the timer logic.

Form1 code:

TimerCalls timerCalls = new TimerCalls();

public SMS()
{
InitializeComponent();
timerCalls.InitializeTimer();
}


Form2 code:

TimerCalls timerCalls = new TimerCalls();

public Form2()
{
InitializeComponent();
}

private void btnSendOn_Click(object sender, EventArgs e)
{
timerCalls.sendTimer.Start();
}

private void btnSendOff_Click(object sender, EventArgs e)
{
timerCalls.sendTimer.Stop();
}


TimerCalls class code:

class TimerCalls
{
public System.Timers.Timer sendTimer = new System.Timers.Timer();
public System.Timers.Timer recTimer = new System.Timers.Timer();

public void InitializeTimer()
{
// Send timer
sendTimer.Elapsed += new ElapsedEventHandler(sendProcessTimerEvent);
sendTimer.Interval = 3000;
//rec timer
recTimer.Elapsed += new ElapsedEventHandler(recProcessTimerEvent);
recTimer.Interval = 3000;
}

private void sendProcessTimerEvent(object sender, EventArgs e)
{
MessageBox.Show("Send 3 sec");
}

private void recProcessTimerEvent(object sender, EventArgs e)
{
MessageBox.Show("Rec 3 sec");
}
}


This is the problem: I open form2, start the timer, close form2, open it again and try to stop the timer it doesn't stop it. Once I reopen the form2, all I can do is start and stop a new timer, but the previous one is still running. Everything works fine (timer starting and stopping) until I close form2. If the timer was on when I closed the form I can't stop it once I open the form2 again.

How can I fix this?

Answer

Assuming you are closing the form, and then creating a new one then yes, it will create multiple instances of Form2.

The best approach as suggested by others would be to use a singleton pattern for TimerCalls and just get the instance in your Form2.

If this sounds like too much work, simply hide Form2 instead of closing it:

private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
    if (e.CloseReason != CloseReason.UserClosing)
        return;
    e.Cancel = true;
    Hide();
}

Then just make sure when you click the button to reopen Form2, you just show the previously created one - which will be something like this.

public class Form1 : Form
{
    private Form2 mForm2;

    protected void OpenForm2_Click(object sender, EventArgs e)
    {
       if (mForm2 == null)  
           mForm2 = new Form2();
       mForm2.Show();
    }
}
Comments