我试图让sslStream异步读取5秒钟。如果流在5秒后没有收到任何内容,则流将被关闭。
当前实现的问题是使用此技巧关闭流将在控制台上发出错误:无法访问已处置的对象。
如果没有此错误,还有其他方法可以实现我的目标吗?
这是我的代码:
private static async Task<string> ReadMessageAsync(SslStream pSslStream)
{
byte[] buffer = new byte[2048];
StringBuilder messageData = new StringBuilder();
int bytes = -1;
try
{
do
{
bytes = await pSslStream.ReadAsync(buffer, 0, buffer.Length)
.TimeoutAfter(TimeSpan.FromSeconds(5));
Decoder decoder = Encoding.UTF8.GetDecoder();
char[] chars = new char[decoder.GetCharCount(buffer, 0, bytes)];
decoder.GetChars(buffer, 0, bytes, chars, 0);
messageData.Append(chars);
if (messageData.ToString().IndexOf("<EOF>") != -1)
{
break;
}
} while (bytes != 0);
}
catch (TimeoutException)
{
Console.WriteLine("Timeout");
pSslStream.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return messageData.ToString();
}
public static async Task<T> TimeoutAfter<T>(this Task<T> task, TimeSpan timeout)
{
if (task != await Task.WhenAny(task, Task.Delay(timeout)))
{
throw new TimeoutException("Timeout");
}
return task.Result;
}
P / s:扩展方法来自How do you catch CancellationToken.Register callback exceptions?