Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
90 views
in Technique[技术] by (71.8m points)

c# - How to "Use of unassigned local variable"?

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?

question from:https://stackoverflow.com/questions/65880569/how-to-use-of-unassigned-local-variable

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...