Код: Выделить всё
static async Task Main(string[] args)
{
string licenseKey = Environment.GetEnvironmentVariable("LICENSE_KEY");
if (string.IsNullOrEmpty(licenseKey))
{
Console.WriteLine("LICENSE_KEY not found.");
return;
}
if (args.Contains("--console") || Environment.GetEnvironmentVariable("RUN_AS_SERVICE") != "true")
{
Console.WriteLine("Running as console.");
var cancellationTokenSource = new CancellationTokenSource();
var task = RunAsConsoleAsync(cancellationTokenSource.Token);
await task;
}
else
{
Console.WriteLine("Running as Windows service.");
RunAsWindowsService();
}
}
Вот мой код для поддержки запуска программы как службы:
Код: Выделить всё
static void RunAsWindowsService()
{
EventLog eventLog = new EventLog();
if (!EventLog.SourceExists("TelegramBotService"))
{
EventLog.CreateEventSource("TelegramBotService", "Application");
}
eventLog.Source = "TelegramBotService";
eventLog.Log = "Application";
HostFactory.Run(x =>
{
x.Service(s =>
{
s.ConstructUsing(name => new TelegramBotService(eventLog));
s.WhenStarted(tc =>
{
try
{
Task.Run(() => tc.StartAsync()).GetAwaiter().GetResult();
eventLog.WriteEntry("Service started successfully.", EventLogEntryType.Information);
}
catch (Exception ex)
{
eventLog.WriteEntry($"Error saat menjalankan service: {ex.Message}", EventLogEntryType.Error);
}
});
s.WhenStopped(tc =>
{
try
{
tc.Stop();
eventLog.WriteEntry("Service stopped successfully.", EventLogEntryType.Information);
}
catch (Exception ex)
{
eventLog.WriteEntry($"Error saat menghentikan service: {ex.Message}", EventLogEntryType.Error);
}
});
});
x.RunAsLocalSystem();
x.SetDescription("Telegram Bot Service");
x.SetDisplayName("TelegramBotService");
x.SetServiceName("TelegramBotService");
// Pengaturan agar service mulai otomatis dan bisa recovery
x.StartAutomatically();
x.EnableServiceRecovery(r => r.RestartService(1)); // Restart setelah 1 menit jika terjadi kesalahan
});
}
Подробнее здесь: https://stackoverflow.com/questions/789 ... -sharp-net