Auto Reconnect When Using StreamingSubscriptionConnection in EWS

c#, ews-managed-api, exchangewebservices

Solution

Remove the `Sleep` call - just immediately reconnect (`connection.Open`). See related SO post. Microsoft also recommends this process of automatic reconnect in their forums.

I would also increase the disconnect interval to 30 minutes to avoid constant opening and closing of the connection. With a one minute disconnect, you may as well be using Pull Subscriptions.

You should also handle the `OnSubscriptionError` to capture when there are errors with your streaming subscription.

Problem

I've created a small app that watches an inbox using the EWS managed dll. When I create the `StreamingSubscriptionConnection` I pass in a 1 minute disconnect. Then in the on disconnect event handler, I sleep for 45 seconds and reconnect. If anything is sent to the inbox in the 45 second sleep period, it originally appeared as if it woke up and fired the `NotificationEventDelegate` properly. However after some testing it appears to fire it multiple times for the same email when more than one email arrives. If I do not sleep then I don't have this problem. So my questions are, why would the `NotificationEventDelegate` not function properly on reconnect, and is there a problem with immediately reconnecting? my code is as follows, ``` 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; } } } ```

Original source

Related problems