Adding setting for automated session serialization on shutdown

- adding automated session serialization on application ending (console or shutdown/logoff)
- adding console class for managing system events
This commit is contained in:
FlorianDahn 2020-04-21 21:45:21 +02:00
parent eebb5cb6f5
commit efe5fef7d0
3 changed files with 79 additions and 0 deletions

View File

@ -75,6 +75,7 @@ namespace TelegramBotBase
SetSetting(eSettings.NavigationMaximum, 10);
SetSetting(eSettings.LogAllMessages, false);
SetSetting(eSettings.SkipAllMessages, false);
SetSetting(eSettings.SafeSessionsOnConsoleExit, false);
this.BotCommands = new List<BotCommand>();
@ -166,6 +167,15 @@ namespace TelegramBotBase
this.Sessions.LoadSessionStates(this.StateMachine);
}
//Enable auto session safe
if (this.GetSetting(eSettings.SafeSessionsOnConsoleExit, false))
{
TelegramBotBase.Tools.Console.SetHandler(() =>
{
this.Sessions.SaveSessionStates(this.StateMachine);
});
}
this.Client.TelegramClient.StartReceiving();
}

View File

@ -24,6 +24,10 @@ namespace TelegramBotBase.Enums
SkipAllMessages = 3,
/// <summary>
/// Does stick to the console event handler and safes all sessions on exit.
/// </summary>
SafeSessionsOnConsoleExit = 4

View File

@ -0,0 +1,65 @@
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
namespace TelegramBotBase.Tools
{
public static class Console
{
[DllImport("Kernel32")]
private static extern bool SetConsoleCtrlHandler(EventHandler handler, bool add);
private delegate bool EventHandler(CtrlType sig);
static EventHandler _handler;
static List<Action> Actions = new List<Action>();
enum CtrlType
{
CTRL_C_EVENT = 0,
CTRL_BREAK_EVENT = 1,
CTRL_CLOSE_EVENT = 2,
CTRL_LOGOFF_EVENT = 5,
CTRL_SHUTDOWN_EVENT = 6
}
static Console()
{
}
public static void SetHandler(Action action)
{
Actions.Add(action);
if (_handler != null)
return;
_handler += new EventHandler(Handler);
SetConsoleCtrlHandler(_handler, true);
}
private static bool Handler(CtrlType sig)
{
switch (sig)
{
case CtrlType.CTRL_C_EVENT:
case CtrlType.CTRL_LOGOFF_EVENT:
case CtrlType.CTRL_SHUTDOWN_EVENT:
case CtrlType.CTRL_CLOSE_EVENT:
foreach (var a in Actions)
{
a();
}
return false;
default:
return false;
}
}
}
}