c#-在EWS中使用StreamingSubscriptionConnection时自动重新连接
作者:互联网
我创建了一个小应用程序,可以使用EWS托管dll监视收件箱.
当我创建StreamingSubscriptionConnection时,我传递了1分钟的断开连接.
然后在断开连接事件处理程序中,我睡了45秒钟,然后重新连接.
如果在45秒的睡眠时间内将任何内容发送到收件箱,它最初看上去就像是醒来并正确触发了NotificationEventDelegate.但是,经过一些测试,当收到多封电子邮件时,它似乎会对同一封电子邮件多次触发.
如果我不睡觉,那么我就不会有这个问题.所以我的问题是,为什么NotificationEventDelegate在重新连接时无法正常运行,并且立即重新连接是否存在问题?
我的代码如下
private MailDirectorServer()
{
_isRunning = false;
ExchangeService _service = new ExchangeService()
{
Credentials = new WebCredentials(userName, password),
Url = new Uri(uriAddress)
};
_connection =
new StreamingSubscriptionConnection(_service, 1);
// set up subscriptions here.
_connection.OnNotificationEvent +=
new StreamingSubscriptionConnection.NotificationEventDelegate(OnNewMail);
_connection.OnDisconnect +=
new StreamingSubscriptionConnection.SubscriptionErrorDelegate(OnDisconnect);
_connection.Open();
_isRunning = true;
}
private void OnDisconnect(object sender, SubscriptionErrorEventArgs args)
{
while (true)
{
if (_isRunning)
{
//_logger.Debug("Sleeping for 45 seconds");
//Thread.Sleep(new TimeSpan(0, 0, 45));
_connection.Open();
_logger.Info("Connection Re Opened");
break;
}
else
{
_logger.Info("Closing Down");
break;
}
}
}
解决方法:
删除Sleep呼叫-只需立即重新连接(connection.Open).请参阅related SO post.Microsoft也为recommends this process of automatic reconnect in their forums.
我还将断开间隔延长到30分钟,以避免持续打开和关闭连接.断开一分钟后,您可能还会使用Pull Subscriptions.
您还应处理OnSubscriptionError
,以在流式传输订阅出现错误时进行捕获.
标签:exchangewebservices,ews-managed-api,c 来源: https://codeday.me/bug/20191127/2076771.html