I downloaded all the messages and checked their attachment . They are filling RAM. I am called that code in threads. I am try to use client.Dispose() and GC.Collect() but is is not helped :((

using (var client = new ImapClient(hostname, true))
{
if (client.Connect( /* optional, use parameters here */ ))
{
// connection successful
if (client.Login(login, pass))
{
// login successful
FolderCollection folders = client.Folders;
int i = 0;
foreach (Folder myfolder in folders)
{
var messages = client.Folders[i].Search("ALL");
i++;
foreach (var message in messages)
{
var attachments = message.Attachments;
if (attachments.Count() > 0)
if (!Directory.Exists(folder + @"\" + login))
{
DirectoryInfo di = Directory.CreateDirectory(folder + @"\" + login);// Try to create the directory.
}
foreach (var attachment in attachments)
{
attachment.Download();
attachment.Save(folder + @"\" + login);
}
}
GC.Collect();
}
}
}
client.Disconnect();
client.Dispose();
}
First of all you are calling
GC.Collect();whenMessageobjects still alive in the current scope.The other problem that you are calling
client.Dispose();butusingstatement do actually the same because it's just syntax sugar for next code:Your example have no memory leaks and GC will collect
Messageobjects on nextCollect()automatically.If you want to force garbage collection you can call
GC.Collect()afterusingblock but it is really bat practice. It is possible to force garbage collection by calling Collect, but most of the time, this should be avoided because it may create performance issues.If it is really necessary to collect object inside the loop you try to use
GCSettings.LargeObjectHeapCompactionModeproperty orWaitForPendingFinalizers()method. Full code will looks like this one:Note that it is not production code but combined workarounds for your problem.