gpt4 book ai didi

c# - 对 TcpClient.ConnectAsync 方法的取消支持

转载 作者:行者123 更新时间:2023-11-30 18:12:01 26 4
gpt4 key购买 nike

我希望得到一些关于为我正在处理的工作增加弹性的意见,该工作涉及异步创建多个 TcpClient 连接到各种服务器,一旦成功建立 TCP 连接,然后存储TcpClient 是一个集合(只是需求的摘录)

这是我目前所拥有的:

internal class Program
{
private static readonly TcpClient _client = new TcpClient(AddressFamily.InterNetwork);
private static SslStream _stream;

private static async Task Main(string[] args)
{
var timeoutTask = Task.Delay(5000);
var connectTask = _client.ConnectAsync("10.14.16.24", 56564);

var completedTask = await Task.WhenAny(timeoutTask, connectTask);
if (completedTask == timeoutTask)
_client.Dispose();

try
{
await connectTask;
_stream = new SslStream(_client.GetStream(), false);
}
catch (SocketException e)
{
Console.WriteLine(e.Message);
}
}
}

问题:如果发生超时,connectTask 状态仍然是“WaitingForActivation”,直到 ConnectAsync 方法返回 FaultedRanToCompletion。如何取消此任务,知道 ConnectAsync 不支持 CancellationToken

欢迎提出任何建议或改进。谢谢

最佳答案

您的里程数可能因您使用的 .net 而异

using System;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;

namespace TcpClientCancellation
{
public static class Extensions
{
public static async Task ConnectAsync(this TcpClient tcpClient, string host, int port, CancellationToken cancellationToken) {
if (tcpClient == null) {
throw new ArgumentNullException(nameof(tcpClient));
}

cancellationToken.ThrowIfCancellationRequested();

using (cancellationToken.Register(() => tcpClient.Close())) {
try {
cancellationToken.ThrowIfCancellationRequested();

await tcpClient.ConnectAsync(host, port).ConfigureAwait(false);
} catch (NullReferenceException) when (cancellationToken.IsCancellationRequested) {
cancellationToken.ThrowIfCancellationRequested();
}
}
}
}
}

关于c# - 对 TcpClient.ConnectAsync 方法的取消支持,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56193767/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com