3

我创建了一个使用 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;
        }
    }
}
4

1 回答 1

3

删除Sleep呼叫 - 立即重新连接 ( connection.Open)。请参阅相关的 SO 帖子。Microsoft 还在他们的论坛中推荐了这种自动重新连接的过程

我还将断开连接间隔增加到30 分钟,以避免不断打开和关闭连接。断开一分钟后,您还不如使用Pull Subscriptions

当您的流媒体订阅出现错误时,您还应该处理OnSubscriptionError捕获。

于 2012-08-23T13:10:19.267 回答