Reputation: 41
I am using Mailkit in a Web.Api application to retrieve mails using ImapClient. I used to connect and disconnect the ImapClient on every API call. However it turns to be very slow, so I decided not to disconnect the client and keep a reference to it by using MemoryCache, and use it on every API call.
I am thinking on calling disconnect at the very moment the user close or leave the web page, however I think it could happens that this event never fires causing that the API never calls Disconnect.
How bad could it be if my application never calls ImapClient.Disconnect? Or Which other approach should I use instead of MemoryCache. Thanks.
Upvotes: 0
Views: 319
Reputation: 41
After some research and trial and error I found a mechanism that I dont know if is the best solution but I share it if someone has a similar situation.
When I register my object in the memory cache I create a policy in the following way:
{
...
cacheService.Set(key, client, CreateItemCachePolicy());
...
}
private CacheItemPolicy CreateItemCachePolicy()
{
CacheItemPolicy p = new CacheItemPolicy();
p.AbsoluteExpiration = DateTimeOffset.Now.Add(TimeSpan.FromHours(1));
p.RemovedCallback = this.RemovedCallback;
return p;
}
private void RemovedCallback(CacheEntryRemovedArguments args)
{
ImapClient client = args.CacheItem.Value as ImapClient;
if (client != null)
{
client.Disconnect(true);
}
}
The memory cache apparently runs in a separate thread and executes periodically the cache cleanup. When the client cache time expires (1 hour) the callback is called and the client gets disconnected.
Upvotes: 1