0

Please, help me to understand how I could stop attempts of executing MethodOne() inside a dispatcherTimer.Tick event handler of WPF DispatcherTimer after first unsuccessful attempt of doing it.

        TimeSpan ts = new TimeSpan(0, 0, 5);
        DispatcherTimer dispatcherTimer = new DispatcherTimer();
        dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
        dispatcherTimer.Interval = ts;
        dispatcherTimer.Start();
 ...

    private void dispatcherTimer_Tick(object sender, EventArgs e)
    {           
        try
        {
           MethodOne()
        }
        catch (Exception)
        {
            // Here I would like prevent code from trying to execute MethodOne()
        }  
    }

I would like to set some lock or to stop timer, but trying to do it I faced problems of visibility of other code from inside a Try-Catch construction and not sure how to overcome it correctly.

rem
  • 16,745
  • 37
  • 112
  • 180

1 Answers1

3

That's what the "sender" argument is for:

private void dispatcherTimer_Tick(object sender, EventArgs e)
{           
    try
    {
       MethodOne()
    }
    catch (Exception)
    {
        (sender as DispatcherTimer).Stop();
    }  
}
JL.
  • 78,954
  • 126
  • 311
  • 459
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536