I'm going to use a Windows Service to send Telegram Messages periodically (Every two minutes). My Windows Service starts fine and after 2 minutes it is stopped. I checked my code and find out it is because of async. How can I solve the problem?
protected override void OnStart(string[] args)
{
//< I declared a System.Timers.Timer to send new Telegram messages.
aTimer = new System.Timers.Timer(120000); // 2 minutes
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
aTimer.Enabled = true;
GC.KeepAlive(aTimer);
//>
}
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
SendNewMessages();
}
async static void SendNewMessages()
{
MyDataContext myDB = new MyDataContext();
var newMessages = myDB.TelegramMessages.Where(tm => tm.Status != "New Message");
foreach (TelegramMessage newMessage in newMessages)
{
try
{
var store = new FileSessionStore();
var client = new TelegramClient(store, "MySession");
await client.Connect();
var res = await client.ImportContactByPhoneNumber(newMessage.ReceiverPhoneNumber);
await client.SendMessage(res.Value, newMessage.Message);
newMessage.Status = "Sent";
myDB.SubmitChanges();
}
catch (Exception ex)
{
newMessage.Status = ex.Message;
myDB.SubmitChanges();
}
Thread.Sleep(5000);
}
}