Skip to content

Commit bfd3177

Browse files
Refactor MailKitClientFactory to remove semaphore and streamline SmtpClient instantiation (#2849)
1 parent 14d7bd9 commit bfd3177

File tree

1 file changed

+8
-19
lines changed

1 file changed

+8
-19
lines changed

docs/extensibility/snippets/MailDevResourceAndComponent/MailKit.Client/MailKitClientFactory.cs

Lines changed: 8 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,6 @@ namespace MailKit.Client;
1111
/// </param>
1212
public sealed class MailKitClientFactory(MailKitClientSettings settings) : IDisposable
1313
{
14-
private readonly SemaphoreSlim _semaphore = new(1, 1);
15-
16-
private SmtpClient? _client;
1714

1815
/// <summary>
1916
/// Gets an <see cref="ISmtpClient"/> instance in the connected state
@@ -29,29 +26,21 @@ public sealed class MailKitClientFactory(MailKitClientSettings settings) : IDisp
2926
public async Task<ISmtpClient> GetSmtpClientAsync(
3027
CancellationToken cancellationToken = default)
3128
{
32-
await _semaphore.WaitAsync(cancellationToken);
33-
29+
var client = new SmtpClient();
3430
try
3531
{
36-
if (_client is null)
32+
if (settings.Endpoint is not null)
3733
{
38-
_client = new SmtpClient();
39-
40-
await _client.ConnectAsync(settings.Endpoint, cancellationToken)
34+
await client.ConnectAsync(settings.Endpoint, cancellationToken)
4135
.ConfigureAwait(false);
4236
}
37+
return client;
4338
}
44-
finally
39+
catch
4540
{
46-
_semaphore.Release();
41+
await client.DisconnectAsync(true, cancellationToken)
42+
client.Dispose();
43+
throw;
4744
}
48-
49-
return _client;
50-
}
51-
52-
public void Dispose()
53-
{
54-
_client?.Dispose();
55-
_semaphore.Dispose();
5645
}
5746
}

0 commit comments

Comments
 (0)