C# 在一定时间后注销用户

C# 在一定时间后注销用户,c#,winforms,timer,logout,C#,Winforms,Timer,Logout,我已经开发了一个windows窗体程序(一个用户登录的电子POS),但作为一项要求,我希望它在30分钟后将用户从系统中注销。我找到了以下代码并对其进行了处理,但我发现了错误: 字段初始值设定项无法引用非静态字段、方法或属性 通过代码中出现的第一个实例\u TimerTick private System.Threading.Timer timer = new System.Threading.Timer( _TimerTick, null, 1000 * 30 * 60,

我已经开发了一个windows窗体程序(一个用户登录的电子POS),但作为一项要求,我希望它在30分钟后将用户从系统中注销。我找到了以下代码并对其进行了处理,但我发现了错误:

字段初始值设定项无法引用非静态字段、方法或属性

通过代码中出现的第一个实例
\u TimerTick

private System.Threading.Timer timer = new System.Threading.Timer(
    _TimerTick,
    null,
    1000 * 30 * 60,
    Timeout.Infinite);

private void _OnUserActivity(object sender, EventArgs e)
{
    if (timer != null)
    {
        timer.Change(1000 * 30 * 60, Timeout.Infinite);
    }
}

private void _TimerTick(object state)
{
    var myLogin = new LoginForm(this);
    myLogin.userCode = null;
    MainControlsPanel.Hide(); 

    // the user has been inactive for 30 minutes; log him out
}

我的意见是在类构造函数中指定计时器:

而不是

private System.Threading.Timer timer = new System.Threading.Timer(
_TimerTick,
null,
1000 * 30 * 60,
Timeout.Infinite);
我会用这样的方法:

    class YourClass
{
private System.Threading.Timer timer;
public YourClass()
{
    timer = new System.Threading.Timer(
    _TimerTick,
    null,
    1000 * 30 * 60,
    Timeout.Infinite);
}
//...
}

或者有办法解决问题

问题就如它所说的那样。将计时器初始化移动到构造函数。