-
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathDefaultTcpSocketFactory.cs
More file actions
60 lines (53 loc) · 1.67 KB
/
DefaultTcpSocketFactory.cs
File metadata and controls
60 lines (53 loc) · 1.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// Copyright (c) BootstrapBlazor & Argo Zhang (argo@live.ca). All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
// Website: https://www.blazor.zone or https://argozhang.github.io/
using System.Collections.Concurrent;
using System.Runtime.Versioning;
namespace BootstrapBlazor.TcpSocket;
[UnsupportedOSPlatform("browser")]
sealed class DefaultTcpSocketFactory(IServiceProvider provider) : ITcpSocketFactory
{
private readonly ConcurrentDictionary<string, ITcpSocketClient> _pool = new();
public ITcpSocketClient GetOrCreate(string name, Action<TcpSocketClientOptions> valueFactory)
{
return _pool.GetOrAdd(name, key =>
{
var options = new TcpSocketClientOptions();
valueFactory(options);
var client = new DefaultTcpSocketClient(options)
{
ServiceProvider = provider,
};
return client;
});
}
public ITcpSocketClient? Remove(string name)
{
ITcpSocketClient? client = null;
if (_pool.TryRemove(name, out var c))
{
client = c;
}
return client;
}
private async ValueTask DisposeAsync(bool disposing)
{
if (disposing)
{
// 释放托管资源
foreach (var socket in _pool.Values)
{
await socket.DisposeAsync();
}
_pool.Clear();
}
}
/// <summary>
/// <inheritdoc/>
/// </summary>
public async ValueTask DisposeAsync()
{
await DisposeAsync(true);
GC.SuppressFinalize(this);
}
}