AuthenticateAsServerAsync 挂起 [英] AuthenticateAsServerAsync hangs

查看:51
本文介绍了AuthenticateAsServerAsync 挂起的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用

await stream.AuthenticateAsServerAsync(serverCert, true, SslProtocols.Tls, false);

在我的应用程序中以保护连接.不幸的是,在极少数情况下(大约是千分之一),这会完全挂起.我试图在较低级别的 NetworkStreamTcpClient 上设置超时.

In my application to secure a connection. Unfortunately in rare cases (roughly one out of 1000) this hangs completely. I tried to set timeouts on the lower level NetworkStream and the TcpClient.

但没有任何效果,这些联系会随着时间的推移不断积累.

But nothing works, those connections keep accumulating over time.

它完全挂起是指它会卡在里面好几天(如果应用程序运行那么长时间).

And by it hangs completely I mean it gets stuck inside there for days (if the application runs that long).

我目前通过一个肮脏的黑客解决了这个问题.我开始一个新线程,在里面等待 5 秒,如果调用没有及时返回,我调用 tcpClient.Close() 强制 SslStream 中止.

I currently solved this with a dirty hack. Im starting a new thread, wait 5seconds inside it, and if the call didnt return in time I call tcpClient.Close() to force the SslStream to abort.

这里有什么问题?一般而言,处理此类场景的预期方法是什么,您需要在函数上超时,但没有需要 TimeSpan 或 CancellationToken 的重载?

Whats the issue here? What is the intended way to handle scenarios like this in general where you need a timeout on a function but there is no overload that takes a TimeSpan or CancellationToken?

tcpClient 上的较低级别超时不应至少抛出异常吗?为什么这也没有发生?

Shouldnt the lower level timeouts on the tcpClient at least throw an exception? Why is that not happening either?

推荐答案

原因

似乎所有与网络相关的东西的异步版本都不支持超时.这就是 AuthenticateAsServerAsync 也不支持超时的原因.

Reason

Seems like the async versions of all network related stuff does not support timeouts. Thats why AuthenticateAsServerAsync does not support timeouts either.

来自文档:

注意

此属性仅影响通过调用 Read 方法执行的同步读取.此属性不影响通过调用 BeginRead 方法执行的异步读取.

This property affects only synchronous reads performed by calling the Read method. This property does not affect asynchronous reads performed by calling the BeginRead method.

我是如何解决的

在我开始 AuthenticateAsServerAsync(...) 之前,我首先延迟启动我自己的任务.

How I solved it

Before I start AuthenticateAsServerAsync(...) I first start my own Task with an delay.

Task.Run(async() {
    await Task.Delay(TimeSpan.FromMinutes(1));
    tcpClient.Close();
});

如果有人有更好的方法来做到这一点,请告诉我:)

If someone has a better way to do this please let me know :)

这篇关于AuthenticateAsServerAsync 挂起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆