简体   繁体   English

一次只允许每个用户一次登录

[英]Only allow a single login per user at a time

I am planning to code an application in C# that will only allow a single logged in user connection at a time. 我打算用C#编写一个应用程序,该应用程序一次只允许一个登录用户连接。 I will have a bit column in my SQL Database called LoggedOn and when logging in I will make it check if the database says loggedon = true such as. 我将有一个bit我叫LoggedOn SQL数据库列,并在登录时,我会让它检查数据库说loggedon = true如。

if (Loggedon == true) {
    //Login things
} else {
    //it appears you are already logged on.
}

My problem is what if my program unexpectedly shuts down? 我的问题是,如果我的程序意外关闭该怎么办?

For example: Force shutdown or task manager end process, how can I run a query before someone does that to prevent no changes to my database. 例如:强制关闭或任务管理器结束进程,如何在有人这样做之前运行查询,以防止对我的数据库进行任何更改。

I am not sure if I explained this well enough but heres my code 我不确定我是否解释得足够好,但是这是我的代码

   protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        string myConnection = "******;";
        MySqlConnection conn = new MySqlConnection(myConnection);
        conn.Open();
        MySqlCommand comm = conn.CreateCommand();
        comm.CommandText = "INSERT INTO users LoggedOn = 'False' where username = '" + Form1.TextBoxText + "'";
        comm.ExecuteNonQuery();
        conn.Close();
        base.Dispose(disposing);
    }

Will this code cover all unexpected closes?is there any alternative easy fast ways of doing this? 这段代码会覆盖所有意外关闭吗?是否有其他简便快捷的方法?

Would an eventhandler fix my issue? 事件处理程序可以解决我的问题吗? such as this: http://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception.aspx 例如: http : //msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception.aspx

Along with the singleton and Loggedon persistance the following will help solve the application crashing scenarios: 连同单例和Loggedon持久性,以下内容将有助于解决应用程序崩溃的情况:

If you want persist Loggedon in the database to ensure the user is not logged on to the system from anywhere else in the world you can have a heartbeat timer to keep the value of Loggedon updated. 如果您希望将Loggedon持久保存在数据库中以确保用户没有从世界其他任何地方登录到系统,则可以使用心跳计时器以使Loggedon的值保持更新。 So ever few minutes the client will update the db to indicate user is still logged on. 因此,每隔几分钟,客户端将更新数据库以指示用户仍在登录。 This will handle the situations in which the application is crashed. 这将处理应用程序崩溃的情况。

There are other ways like: You could logoff all other sessions of the user if a user logs in again. 还有其他类似的方法:如果用户再次登录,则可以注销该用户的所有其他会话。 Or you can have a watchdog timer instead of a heartbeat - very similar but watchdog essentially ensures long running sessions are infact active 或者,您可以使用看门狗计时器来代替心跳-非常相似,但是看门狗实质上可以确保长时间运行的会话实际上处于活动状态

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

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