I am trying to let sslStream read asynchronously for 5 seconds. If the stream received nothing after 5 seconds, the stream will be closed.
The problem of current implementation is that closing the stream using this trick will emit an error on console saying: Cannot access a disposed object.
Is there any other way to achieve my goal without this error?
Here's my code:
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: The extension method was from How do you catch CancellationToken.Register callback exceptions?