简体   繁体   English

如何“使用未分配的局部变量”?

[英]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.我正在使用此代码,但在调用 Tick 方法时出现以下错误:使用未分配的局部变量。

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();当我在 else 子句中放置_dispatcherTimer.Dispose();时发生错误but how can I make it work without deleting this line?但是如何在不删除此行的情况下使其工作?

The _dispatcherTimer must be defined before the Tick delegate, but needs not be started until after timerDelegate is created. _dispatcherTimer必须在Tick委托之前定义,但在创建timerDelegate之后才需要启动。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM