This example demonstrates a way to deal with connection resets while receiving IMAP IDLE notifications.

Handling disconnects during IDLE.

The S22.Imap library does not attempt to automatically reconnect if the underlying network connection is reset or the server unexpectedly closes the connection while listening for IMAP IDLE notifications. Instead it raises the [S22.Imap.ImapClient.IdleError] event to which you can subscribe in order to learn the reason for the connection reset and then deal with the situation as you see fit.

The following naive example demonstrates how to perform an automatic reconnect if the connection to the server is lost.

CopyC#
using S22.Imap;
using System;

namespace ConsoleApplication1 {
    class Program {
        static AutoResetEvent reconnectEvent = new AutoResetEvent(false);
        static ImapClient client;

        static void Main(string[] args) {
            try {
                while (true) {
                    Console.Write("Connecting...");
                    InitializeClient();
                    Console.WriteLine("OK");

                    reconnectEvent.WaitOne();
                }
            } finally {
                if (client != null)
                    client.Dispose();
            }
        }

        static void InitializeClient() {
            // Dispose of existing instance, if any.
            if (client != null)
                client.Dispose();
            client = new ImapClient("imap.gmail.com", 993, "username", "password", AuthMethod.Login, true);
            // Setup event handlers.
            client.NewMessage += client_NewMessage;
            client.IdleError += client_IdleError;
        }

        static void client_IdleError(object sender, IdleErrorEventArgs e) {
            Console.Write("An error occurred while idling: ");
            Console.WriteLine(e.Exception.Message);

            reconnectEvent.Set();
        }

        static void client_NewMessage(object sender, IdleMessageEventArgs e) {
            Console.WriteLine("Got a new message, uid = " + e.MessageUID);
        }
    }
}