我有这个代码连接到流媒体服务器。服务器不时断开连接,我想检测它并在neede时重新启动连接。
如何在此代码中检测到任何类型的异常?
因为现在我断开连接而无法抓住它。
this.ns = new NetworkStream(server);
while (true)
{
// Incoming message may be larger than the buffer size.
do
{
byte[] myReadBuffer = new byte[10240 * 5];
await this.ns.ReadAsync(myReadBuffer, 0, myReadBuffer.Length).ContinueWith((numberOfBytesRead) =>
{
string message = Encoding.ASCII.GetString(myReadBuffer, 0, numberOfBytesRead.Result);
p.Invoke(message);
});
}
while (this.ns.DataAvailable);
}
答案 0 :(得分:1)
您的变量numberOfBytesRead
实际上是上一个完成的任务,您可以从中检查它是完成还是失败。
if(numberOfBytesRead.IsFaulted)
{
var aggregatedEx = numberOfBytesRead.Exception;
//do something
}