本文介绍了如何从ElapsedEventHandler调用异步方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要使用Windows服务来发送定期电报消息(每两分钟)。我的Windows服务启动罚款,被停止2分钟后。我检查了我的代码,并发现它是因为异步的。我怎样才能解决这个问题?
保护覆盖无效的OnStart(字串[] args)
{
//<我宣布System.Timers.Timer发送新电报消息。
aTimer =新System.Timers.Timer(120000); //2分钟
aTimer.Elapsed + =新ElapsedEventHandler(OnTimedEvent);
aTimer.Enabled = TRUE;
GC.KeepAlive(aTimer);
//>
}
私有静态无效OnTimedEvent(对象源,ElapsedEventArgs E)
{
SendNewMessages();
}
异步静态无效SendNewMessages()
{
MyDataContext MYDB =新MyDataContext();
VAR newMessages = myDB.TelegramMessages.Where(TM =>!tm.Status =新邮件);
的foreach(TelegramMessage NewMessage作为在newMessages)
{
试
{
变种店=新FileSessionStore();
VAR的客户=新TelegramClient(店MySession的);
等待client.Connect();
VAR解析度=等待client.ImportContactByPhoneNumber(newMessage.ReceiverPhoneNumber);
等待client.SendMessage(res.Value,newMessage.Message);
newMessage.Status =已发送;
myDB.SubmitChanges();
}
赶上(异常前)
{
newMessage.Status = ex.Message;
myDB.SubmitChanges();
}
Thread.sleep代码(5000);
}
}
解决方案
一我直接看到的是异步/伺机尚未一路以来SendNewMessages落实到事件处理程序返回void。和你的事件处理程序是不是异步。
的
This is most likely an issue in your scenario, so you could try changing your SendNewMessage to this
async static Task SendNewMessages()
And your eventhandler to this
private async static void OnTimedEvent(object source, ElapsedEventArgs e)
{
await SendNewMessages();
}
UPDATED
It would also be a good idea to add some errorhandling code to your "SendNewMessages"-method since if an exception is thrown, your service will quit.
async static Task SendNewMessages()
{
try
{
... Your code here
}
catch(Exception e)
{
... exceptionhandling here
}
}
At the moment you only have exceptionhandling within your foreach, but you do not have any errorhandling (as far as I can see) for your database-code.
if an exception is throw here
MyDataContext myDB = new MyDataContext();
var newMessages = myDB.TelegramMessages.Where(tm => tm.Status != "New Message");
foreach (TelegramMessage newMessage in newMessages)
or here:
newMessage.Status = ex.Message;
myDB.SubmitChanges();
The service would end
这篇关于如何从ElapsedEventHandler调用异步方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!