Skip to content

Commit

Permalink
#72 fix cancellation token disposed excpetion
Browse files Browse the repository at this point in the history
  • Loading branch information
danzuep committed Sep 8, 2024
1 parent cbbd242 commit 37bf855
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 12 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,11 @@ public class FolderMonitorOptions
/// </summary>
public ushort EmptyQueueMaxDelayMs { get; set; } = 500;

/// <summary>
/// The length of time the receiver will delay for between retry attempts after an exception.
/// </summary>
public ushort ExceptionRetryDelaySeconds { get; set; } = 2;

public override string ToString() => $"MessageSummaryItems={MessageSummaryItems}, IgnoreExisting={IgnoreExistingMailOnConnect}, IdleMinutes={IdleMinutes}, MaxRetries={MaxRetries}.";
}
}
25 changes: 13 additions & 12 deletions source/MailKitSimplified.Receiver/Services/MailFolderMonitor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -305,15 +305,16 @@ private void Disconnect(bool throwOnFirstException)
_mailFolder.CountChanged -= OnCountChanged;
}

_arrival?.Cancel(throwOnFirstException);
_cancel?.Cancel(throwOnFirstException);
_messageCache?.Clear();
#if NET6_0_OR_GREATER
_arrivalQueue?.Clear();
_departureQueue?.Clear();
_flagChangeQueue?.Clear();
#endif
_arrival?.Dispose();
_cancel?.Dispose();
//_arrival?.Dispose();
//_cancel?.Dispose();
}

/// <exception cref="AuthenticationException">Failed to authenticate</exception>
Expand Down Expand Up @@ -358,15 +359,15 @@ private async ValueTask ReconnectAsync(CancellationToken cancellationToken = def
async ValueTask LogDelayAsync(Exception exception, string exceptionType)
{
bool isBackoff = attemptCount > 0 && attemptCount < _folderMonitorOptions.MaxRetries;
var backoffDelay = _folderMonitorOptions.EmptyQueueMaxDelayMs ^ attemptCount;
var backoff = isBackoff ? $", backing off for {backoffDelay}ms" : string.Empty;
var backoffDelay = _folderMonitorOptions.ExceptionRetryDelaySeconds ^ attemptCount;
var backoff = isBackoff ? $", backing off for {backoffDelay} seconds" : string.Empty;
var message = $"{_imapReceiver} {exceptionType} during connection attempt #{++attemptCount}{backoff}.";
if (attemptCount < _folderMonitorOptions.MaxRetries)
_logger.Log<MailFolderMonitor>(message, LogLevel.Information);
else
throw exception; // TODO fix this, it changes the stacktrace parameter
if (isBackoff)
await Task.Delay(backoffDelay, cancellationToken).ConfigureAwait(false);
await Task.Delay(TimeSpan.FromSeconds(backoffDelay), cancellationToken).ConfigureAwait(false);
}
}
}
Expand Down Expand Up @@ -435,7 +436,7 @@ private async ValueTask WaitForNewMessagesAsync(CancellationToken cancellationTo
}
catch (InvalidOperationException ex)
{
_logger.Log<MailFolderMonitor>(ex, $"{_imapReceiver} IMAP client is being accessed by multiple threads.");
_logger.Log<MailFolderMonitor>(ex, $"{_imapReceiver} IMAP client is probably being accessed by multiple threads.");
_cancel.Cancel(false);
break;
}
Expand Down Expand Up @@ -502,9 +503,9 @@ private async Task ProcessArrivalQueueAsync(Func<IMessageSummary, Task> messageA
{
if (messageSummary != null)
_arrivalQueue.Enqueue(messageSummary);
var backoff = _folderMonitorOptions.EmptyQueueMaxDelayMs ^ retryCount;
var backoff = _folderMonitorOptions.EmptyQueueMaxDelayMs * retryCount;
_logger.Log<MailFolderMonitor>(ex, $"{_imapReceiver} Error occurred processing arrival queue item ({messageSummary?.UniqueId}) during attempt #{retryCount}, backing off for {backoff}ms.", LogLevel.Warning);
await Task.Delay(_folderMonitorOptions.EmptyQueueMaxDelayMs, cancellationToken).ConfigureAwait(false);
await Task.Delay(backoff, cancellationToken).ConfigureAwait(false);
}
}
while (!cancellationToken.IsCancellationRequested && retryCount < _folderMonitorOptions.MaxRetries);
Expand Down Expand Up @@ -537,9 +538,9 @@ private async Task ProcessDepartureQueueAsync(Func<IMessageSummary, Task> messag
{
if (messageSummary != null)
_departureQueue.Enqueue(messageSummary);
var backoff = _folderMonitorOptions.EmptyQueueMaxDelayMs ^ retryCount;
var backoff = _folderMonitorOptions.EmptyQueueMaxDelayMs * retryCount;
_logger.Log<MailFolderMonitor>(ex, $"{_imapReceiver} Error occurred processing departure queue item ({messageSummary?.UniqueId}) during attempt #{retryCount}, backing off for {backoff}ms.", LogLevel.Warning);
await Task.Delay(_folderMonitorOptions.EmptyQueueMaxDelayMs, cancellationToken).ConfigureAwait(false);
await Task.Delay(backoff, cancellationToken).ConfigureAwait(false);
}
}
while (!cancellationToken.IsCancellationRequested && retryCount < _folderMonitorOptions.MaxRetries);
Expand Down Expand Up @@ -579,9 +580,9 @@ private async Task ProcessFlagChangeQueueAsync(Func<IMessageSummary, Task> messa
{
if (messageSummary != null)
_flagChangeQueue.Enqueue(messageSummary);
var backoff = _folderMonitorOptions.EmptyQueueMaxDelayMs ^ retryCount;
var backoff = _folderMonitorOptions.EmptyQueueMaxDelayMs * retryCount;
_logger.Log<MailFolderMonitor>(ex, $"{_imapReceiver} Error occurred processing flag change queue item ({messageSummary?.UniqueId}) during attempt #{retryCount}, backing off for {backoff}ms.", LogLevel.Warning);
await Task.Delay(_folderMonitorOptions.EmptyQueueMaxDelayMs, cancellationToken).ConfigureAwait(false);
await Task.Delay(backoff, cancellationToken).ConfigureAwait(false);
}
}
while (!cancellationToken.IsCancellationRequested && retryCount < _folderMonitorOptions.MaxRetries);
Expand Down

0 comments on commit 37bf855

Please sign in to comment.