问题
First I have a table UserAccounts with Column LoginStatus if the user logged in the user loginstatus = 1 else if he logged out it is = 0
what code do you think that will handle if the user accidentally plug off the computer or a power failure occurs. i need to change the loginstatus = 0 or it will auto logout if those events occurs.
by the way im using sql server
i've used this code in form closing but it only change the loginstatus if i shutdown computer from start menu directly while the application is running
private void MPTestTablesFormClosing(object sender, FormClosingEventArgs e)
{
if(e.CloseReason == CloseReason.WindowsShutDown)
{
var repo = new UserAccountsRepo();
var backRepo = new UserLogRepo();
var logs = new UserLogs
{
UserAccount = Globals.UserAccount,
LogOutTime = DateTime.Now
};
Globals.UserAccount.LogStatus = 0;
repo.Update(Globals.UserAccount);
backRepo.Update(logs);
Globals.UserAccount = null;
}
}
回答1:
One possible solution is to keep track of the fact that your application did not close cleanly. I..e have a flag saved somewhere in a persistent medium that gets set at start-up of your application, and that gets reset when your application exists cleanly.
Then at startup check this flag. If it is still set, you known that your application did not exit cleanly, and you can take appropriate (recovery) steps to get back into a stable non-corrupted situation.
回答2:
Handling sudden power failures in an application running on the computer with the power failure simply isn't possible. When the power fails the computer will stop running and the application will receive no warning.
For cases where the power mode changes, as in computer being suspended or shut down, you can use the following events on SystemEvents
SystemEvents.PowerModeChangedSystemEvents.SessionEnding
Both of these can be raised in response to specific power events on the computer. This may be what you are looking for
来源:https://stackoverflow.com/questions/18421702/unlogged-out-user-if-power-failures-unplugging-computer-how-to-handle-power-fai