When I use several ImapClient instances in several instances of a class that uses a System.Timers.Timer to check a specific IMAP mailbox it runs into trouble. This code hangs itself somewhere in the Aspose.Email.dll when running in the thread created by the .NET Timer class:
try
{
using (var imapClient = CreateImapClient())
{
var imapFolderInfo = imapClient.ListFolder(Folder);
if (imapFolderInfo.TotalMessageCount > 0)
{
// Select the configured folder
imapClient.SelectFolder(Folder);
// Get a list of messages
var imapMessageInfoCollection = imapClient.ListMessages();
// Traverse the list and process the emails
foreach (var imapMessageInfo in imapMessageInfoCollection)
{
using (var mailMessage = imapClient.FetchMessage(imapMessageInfo.UniqueId))
{
if (TransferEmail(Name, mailMessage))
{
imapClient.DeleteMessage(imapMessageInfo.UniqueId);
}
}
}
}
imapClient.Disconnect();
}
}
Adding a lock fixes it:
try
{
lock (ImapClientLock)
{
using (var imapClient = CreateImapClient())
{
var imapFolderInfo = imapClient.ListFolder(Folder);
if (imapFolderInfo.TotalMessageCount > 0)
{
// Select the configured folder
imapClient.SelectFolder(Folder);
// Get a list of messages
var imapMessageInfoCollection = imapClient.ListMessages();
// Traverse the list and process the emails
foreach (var imapMessageInfo in imapMessageInfoCollection)
{
using (var mailMessage = imapClient.FetchMessage(imapMessageInfo.UniqueId))
{
if (TransferEmail(Name, mailMessage))
{
imapClient.DeleteMessage(imapMessageInfo.UniqueId);
}
}
}
}
imapClient.Disconnect();
}
}
}
When it hangs, it keeps producing one or more of these exceptions (shown in the debugger output window) per second:
A first chance exception of type ‘System.IO.IOException’ occurred in Aspose.Email.dll
A first chance exception of type ‘System.IO.IOException’ occurred in System.dll
A first chance exception of type ‘System.IO.IOException’ occurred in Aspose.Email.dll
A first chance exception of type ‘System.IO.IOException’ occurred in System.dll
A first chance exception of type ‘System.IO.IOException’ occurred in Aspose.Email.dll
A first chance exception of type ‘System.IO.IOException’ occurred in System.dll
A first chance exception of type ‘System.IO.IOException’ occurred in Aspose.Email.dll
A first chance exception of type ‘System.IO.IOException’ occurred in System.dll
A first chance exception of type ‘System.IO.IOException’ occurred in Aspose.Email.dll
A first chance exception of type ‘System.IO.IOException’ occurred in System.dll
A first chance exception of type ‘System.IO.IOException’ occurred in Aspose.Email.dll
A first chance exception of type ‘System.IO.IOException’ occurred in System.dll
But it never returns to my TimerElapsed handler.
Adding a lock like this fixes my problem, but introduces the problem of ImapClients waiting for each other to finish. Please advise.