1

我在 Windows 应用程序中创建了一个项目,并为该项目提供了多个用户可访问性,但我需要将其限制为一次只有 3 个用户访问它。为此,我为每次登录status=true和注销添加了列状态(位),status=false但如果我从结束任务和系统关闭结束我的项目,那么我在计算登录用户时遇到问题。

是否可以找到活跃用户和状态?如果可能的话,我将每 5 分钟运行一次触发器并相应地更新状态字段。

4

1 回答 1

0

好的,因为这是一个 Windows 应用程序,并且您没有提供任何代码,所以当他们登录时我会做这样的事情:

// connect to the database
using (SqlConnection c = new SqlConnection("connection string"))
{
    // count the logged in users
    var loggedInUsers = (int)new SqlCommand("SELECT COUNT(UserId) FROM Users WHERE status = 1", c).ExecuteScalar();

    // if the threshold has been met then shut down the application
    if (loggedInUsers == 3)
    {
        MessageBox.Show("There are already 3 concurrent users logged into the system -please try again at a later time.", "User Limit Met", MessageBoxButtons.OK, MessageBoxIcon.Information);
        Application.Exit();
    }
}

但是当应用程序关闭时你也必须这样做,比如在OnClosing主窗体的方法中:

protected override void OnClosing(CancelEventArgs e)
{
    // connect to the database
    using (SqlConnection c = new SqlConnection("connection string"))
    {
        // log the user out
        var cmd = new SqlCommand("UPDATE Users SET status = 0 WHERE UserId = @UserId", c);
        cmd.Parameters.AddWithValue("@UserId", // get your user id from somewhere

        var rowsAffected = cmd.ExecuteNonQuery();

        // make sure the update worked
        if (rowsAffected == 0)
        {
            // do something here to make sure they get logged out
        }
    }
}

编辑

例如,要在任务管理器退出期间处理应用程序失败的边缘情况,您应该能够利用Application.Exit,因此在您的启动方法(即Application.Run调用的位置)中将这一行放在前面:

Application.ApplicationExit += new EventHandler(Application_ApplicationExit);

然后消费它:

private void Application_ApplicationExit(object sender, EventArgs e)
{
    // and now you can probably just move all of the code here
    // instead of the OnClosing
}
于 2013-04-24T13:19:44.443 回答