views:

215

answers:

1

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.

+2  A: 

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

private void dispatcherTimer_Tick(object sender, EventArgs e)
{           
    try
    {
       MethodOne()
    }
    catch (Exception)
    {
        (sender as DispatcherTimer).Stop();
    }  
}
Hans Passant