c# - System.OperationCanceledException 偶尔发生在带有 try catch 的异步函数中
问题描述
全部,
我有一个生产 ASP.NET 核心 2.2 应用程序管理 websockets 连接。如果客户端在传输期间重置连接,我们偶尔会在 try catch 块中遇到未处理的异常错误,这应该是我们可以在代码中处理的条件(我们断开客户端)。
下面代码中的 try catch 块没有捕获偶尔的客户端断开/重置,因为错误在 CoreLib.dll 而不是 C# 代码中,我怀疑这可能与未正确设置异步函数有关?
任何想法是什么导致它,以及如何解决它?
// Process web sockets request
private static async Task<bool> ReceiveBin(MQTT.Broker myClient, CancellationToken ct = default(CancellationToken))
{
var buffer = new ArraySegment<byte>(new byte[RECV_BUFF_SIZE]);
using (var ms = new MemoryStream())
{
WebSocketReceiveResult result = null;
try
{
do
{
ct.ThrowIfCancellationRequested();
result = await myClient.socket.ReceiveAsync(buffer, ct); <== Unhandled exception breaks here
ms.Write(buffer.Array, buffer.Offset, result.Count);
}
while (!result.EndOfMessage);
}
catch (Exception ex) // v1 ASP Core sometimes throw errors when client aborts session
{
CloseWSSess(myClient, "Error receiving from client - resetting session. Error: " + ex.Message);
return false;
}
...
Error from the await statement => An exception of type 'System.OperationCanceledException' occurred in System.Private.CoreLib.dll and wasn't handled before a managed/native boundary
解决方案
推荐阅读
- r - 根据R中的关键字创建类别
- android - 移动应用程序可以连接到 BLE 设备并在后台保持连接数小时吗?
- python - Insert_one 不存在这样的方法@ pymongo 3.7.2
- scala - 为什么数据集的 foreach 方法不需要编码器,但 map 需要?
- amazon-product-api - 当您拥有“即将推出”网站时,可以作为开发人员访问产品广告 API
- c# - 使用 Foreach 循环消耗大量 WebServices
- java - 如何使用扩展房间中另一个类的实体类?
- sql - SQL group by - 可以这么简单吗?
- apache-kafka - 绘制 Kafka+Zookeeper 集群
- python - Python boto3 SNS 电子邮件格式化