我试图通过调用Socket.ReceiveAsync()
并处理不可避免的Socket.Close()
来取消SocketException
通话。
我的问题是调用函数中的异常似乎从未出现在try/catch
中。像这样:
public async Task DoSomethingAsync()
{
Try
{
while(true)
{
await DoSomethingMoreSpecificAsync();
....
}
}
catch(Exception ex)
{
do some logging... <-- exception never makes it here
}
finally
{
cleanup stuff(); <-- or here...
}
}
public async Task DoSomethingMoreSpecificAsync()
{
var read = await _sock.ReceiveAsync(...); <-- Exception is thrown here
}
因此,引发异常时,应用程序永远不会将其置于catch
或finally
块中。它只是抱怨未处理的异常。 AFAIK async Task
方法应像其他任何方法一样向上传播其异常。我知道如果我使用async void
...
在控制台中,应用崩溃后,我看到以下内容:
在抛出“ PAL_SEHException”实例后调用terminate
这是实际代码:
private async Task DoReceiveAsync()
{
var writer = _inputPipe.Writer;
Exception ex = null;
try
{
while (true)
{
var mem = writer.GetMemory(TLS_MAX_RECORD_SIZE);
MemoryMarshal.TryGetArray(mem, out ArraySegment<byte> buf);
//Since OpenSSL will only gve us a complete record, we need a func that will piece one back together from the stream
await ReadRecord(mem);
var res = _ssl.Read(buf.Array, TLS_MAX_RECORD_SIZE);
writer.Advance(res);
var flush = await writer.FlushAsync();
if (flush.IsCanceled || flush.IsCompleted)
break;
}
}
catch (Exception e) { ex = e; }
finally { writer.Complete(ex); }
}
private async Task ReadRecord(Memory<byte> mem)
{
MemoryMarshal.TryGetArray(mem, out ArraySegment<byte> buf);
SslError res;
do
{
var sockRead = await _socket.ReceiveAsync(buf, SocketFlags.None);
if (sockRead == 0) break;
_ssl.ReadBio.Write(buf.Array, sockRead);
var sslRead = _ssl.Peek(peekBuf, TLS_MAX_RECORD_SIZE);
res = _ssl.GetError(sslRead);
} while (res != SslError.SSL_ERROR_NONE);
return;
}