0 votes

How to work with multithread for mail.dll? I always get error like this when fetching the data
"Limilabs.Client.ServerException: 'The Write method cannot be called when another write operation is pending.'"

I try to debug and the first method that cause the error
"Imap.GetBodyStructureByUID();"
It looks like GetBodyStructureByUID() not build for async, can you help me which method or workaround can be used for running fetch in multi thread?

// Bad code - do not use

await Task.Run(() =>
{
Parallel.ForEach(NewEmailHeaderIdList,
 },
 NewEmailHeaderId=>
{
List<BodyStructure> structures = Imap.GetBodyStructureByUID(NewEmailHeaderIdList);

string text = string.Empty;
string html = string.Empty;

if (structure.Text != null)
   text = Imap.GetTextByUID(structure.Text);
if (structure.Html != null)
   html = Imap.GetTextByUID(structure.Html);
}
);
}).ConfigureAwait(false);
by
edited by

1 Answer

0 votes

This has nothing to do with async.

Underneath the Imap class (client) is a single connection to an IMAP server.
You can not write to a single connection from many threads at once - that would result in complete garbage being sent to server.

Now, if you are asking "Does IMAP support multiple connections"?
The answer to that is: yes it does.

You can created several threads and several Imap classes and use them simultaneously.

by (297k points)
Thank you for your fast response.
Sorry, I don't know that get email body(GetBodyStructureByUID) requires write on server.

If I only create desktop mail client for single user to login their email, then I don't need several thread calling several imap. This case only for multiple user to fetch their email simultaneously. Is my understanding correct?
Correct. You could use multiple clients for a single account, for example downloading each folder separately, but in most cases that makes no sense.
...