Search code examples
c#wpfeventsevent-handlingunsubscribe

Unsubscribing event from inside another event


I`m trying to unsubscribe from an event inside another event and I don't have a clue how I should approach this or if there is a simple pattern for this. I already looked in the official Documentation from Microsoft but I did not found anything to solve my problem.

        private void bTrainingD_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Threading.DispatcherTimer timer = new System.Windows.Threading.DispatcherTimer();
            timer.Interval = TimeSpan.FromSeconds(1);
            timer.Tick += new EventHandler(dispatcherTimer_Tick);
            timer.Start();
        }

        ...

        private void dispatcherTimer_Tick(object sender, EventArgs e)
        {
            if (true)
            {
                //some code here
            }
            else
            {
                // unsubscribe or stop the Tick-Event here
            }

        }

Thanks for your help. :-)


Solution

  • you need to keep reference to timer in a class field, not in local variable, to make it accessible in another class method:

    private System.Windows.Threading.DispatcherTimer timer;
    
    private void bTrainingD_Click(object sender, RoutedEventArgs e)
    {
        timer = new System.Windows.Threading.DispatcherTimer();
        timer.Interval = TimeSpan.FromSeconds(1);
        timer.Tick += dispatcherTimer_Tick;
        timer.Start();
    }
    
    private void dispatcherTimer_Tick(object sender, EventArgs e)
    {
        if (true)
        {
            //some code here
        }
        else
        {
            timer.Tick -= dispatcherTimer_Tick;
        }
    }