-1

I am using this code but I get the following error when calling the Tick method: Use of unassigned local variable.

try 
{
    //Something
}catch (Exception e) 
{                
    int sec = 120000; // 2 minutes
    int period = 5000; //every 5 seconds

    TimerCallback timerDelegate = new TimerCallback(Tick);
    System.Threading.Timer _dispatcherTimer = new System.Threading.Timer(timerDelegate, null, period, period);// if you want the method to execute immediately,you could set the third parameter to null

    void Tick(object state)
    {

        Device.BeginInvokeOnMainThread(() =>
        {
            sec -= period;

            if (sec >= 0)
            {
                //do something
            }
            else
            {
                _dispatcherTimer.Dispose();

            }
        });
    }
}

The error occurs when in the else clause I put _dispatcherTimer.Dispose(); but how can I make it work without deleting this line?

Mong Zhu
  • 23,309
  • 10
  • 44
  • 76
LololYut
  • 65
  • 7
  • Can you give the exact error message? The problem is probably related to the fact that you're trying to dispose the timer from within the callback. That will cause trouble. – PMF Jan 25 '21 at 07:40
  • Represents the method that handles calls from a System.Threading.Timer Use of unassigned local variable _dispatcherTimer – LololYut Jan 25 '21 at 07:43
  • "Use of unassigned local variable" is a compile-time error. Is that what you are seeing? – John Wu Jan 25 '21 at 07:57
  • Yes, I can't find a solution. – LololYut Jan 25 '21 at 08:00
  • ok this is weird. On which level is the code situated that instantiates the timer and callback delegate? it cannot be on class level, because you would not be able to use non static fields in the initialization. please provide a code context that is closer to your real code – Mong Zhu Jan 25 '21 at 08:37
  • The code is inside of a catch clause. – LololYut Jan 25 '21 at 08:40

1 Answers1

2

The _dispatcherTimer must be defined before the Tick delegate, but needs not be started until after timerDelegate is created.

    Timer _dispatcherTimer = null;
    TimerCallback timerDelegate = new TimerCallback(Tick);
    _dispatcherTimer = new Timer(timerDelegate, null, period, period);

dxiv
  • 16,984
  • 2
  • 27
  • 49