首页 > 解决方案 > 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

标签: c#asp.net-core

解决方案


推荐阅读