Skip to content
Merged
Original file line number Diff line number Diff line change
Expand Up @@ -556,9 +556,9 @@ Exception ProcessException(Exception e, ref bool canceled, bool forceWrapExcepti

if (!forceWrapExceptions ||
// for compatibility reasons, don't wrap these exceptions during sync executions
(typeof(TIOAdapter) == typeof(SyncReadWriteAdapter) &&
(e is SecurityException || e is AuthenticationException)) ||
e is SmtpException)
(typeof(TIOAdapter) == typeof(SyncReadWriteAdapter) && (e is SecurityException or AuthenticationException)) ||
e is SmtpException ||
e is OperationCanceledException)
{
return e;
}
Expand All @@ -574,7 +574,7 @@ Exception ProcessException(Exception e, ref bool canceled, bool forceWrapExcepti
// SendCompleted event should ever be invoked only for asynchronous send completions.
if (invokeSendCompleted && !synchronous)
{
AsyncCompletedEventArgs eventArgs = new AsyncCompletedEventArgs(exception, canceled, userToken);
AsyncCompletedEventArgs eventArgs = new(canceled ? null : exception, canceled, userToken);
OnSendCompleted(eventArgs);
}
}
Expand Down
14 changes: 4 additions & 10 deletions src/libraries/System.Net.Mail/tests/Functional/SmtpClientTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -314,20 +314,15 @@ public async Task SendMailAsync_CanBeCanceled_CancellationToken()
server.ReceiveMultipleConnections = true;

// The server will introduce some fake latency so that the operation can be canceled before the request completes
ManualResetEvent serverMre = new ManualResetEvent(false);
server.OnConnected += _ => serverMre.WaitOne();

CancellationTokenSource cts = new CancellationTokenSource();

server.OnConnected += _ => cts.Cancel();

var message = new MailMessage("foo@internet.com", "bar@internet.com", "Foo", "Bar");

Task sendTask = Task.Run(() => client.SendMailAsync(message, cts.Token));

cts.Cancel();
await Task.Delay(500);
serverMre.Set();

await Assert.ThrowsAsync<TaskCanceledException>(async () => await sendTask).WaitAsync(TestHelper.PassingTestTimeout);
await Assert.ThrowsAnyAsync<OperationCanceledException>(async () => await sendTask).WaitAsync(TestHelper.PassingTestTimeout);

// We should still be able to send mail on the SmtpClient instance
await Task.Run(() => client.SendMailAsync(message)).WaitAsync(TestHelper.PassingTestTimeout);
Expand Down Expand Up @@ -369,8 +364,7 @@ public async Task SendAsync_CanBeCanceled_SendAsyncCancel()
client.SendAsync(message, null);
AsyncCompletedEventArgs e = await tcs.Task.WaitAsync(TestHelper.PassingTestTimeout);
Assert.True(e.Cancelled, "SendAsync should have been canceled");
_output.WriteLine(e.Error?.ToString() ?? "No error");
Assert.IsType<OperationCanceledException>(e.Error.InnerException);
Assert.Null(e.Error);

// We should still be able to send mail on the SmtpClient instance
await client.SendMailAsync(message).WaitAsync(TestHelper.PassingTestTimeout);
Expand Down
Loading