【问题标题】:Exception Handling in Async Methods异步方法中的异常处理
【发布时间】:2014-04-02 05:46:04
【问题描述】:

我有一个关于在 C# 中长时间等待链后捕获异常的问题。

        /// <summary>
        /// Waiting on this waits on a response, be warned!
        /// </summary>
        /// <param name="msg"></param>
        /// <returns></returns>
         public async Task<ComMessage> SendMessageForResponse(ComMessage msg)
         {
             lock (_responses)
             {
                 _responses[msg.transactionid] = null;
             }

           await SendMessage(msg);

           return await Task.Run<ComMessage>(() => {
                lock (_responses)
                {
                    while (_responses[msg.transactionid] == null) Monitor.Wait(_responses);
                    var response = _responses[msg.transactionid];
                    _responses.Remove(msg.transactionid);
                    return response;
                }

            });


        }

        /// <summary>
        /// Sends a message, serialized as JSON, to the game
        /// </summary>
        /// <param name="msg"></param>
        /// <returns></returns>
        public async Task SendMessage(ComMessage msg)
        {
            try
            {
                await _semaphore.WaitAsync();
                await Task.Run(() => { new DataContractJsonSerializer(msg.GetType()).WriteObject(_writer.BaseStream, msg); });
            }
            finally { _semaphore.Release(); }

        }

new DataContractJsonSerializer(msg.GetType()).WriteObject(_writer.BaseStream, msg); } 引发异常时,我希望调用 await SendMessageForResponse 的方法捕获该异常,例如下面的代码

 try
        {
            var t = await St0rmCom.Instance.SendMessageForResponse(com);


            MessagePlayerInfoResponse pi = (MessagePlayerInfoResponse)t;
            StringBuilder sb = new StringBuilder();
            Debug.LogInfo("Iterating {0} players", pi.playerinfo.Length);
            for (int i = 0, count = 0; i < pi.playerinfo.Length; ++i)
            {
                MessagePlayerData p = pi.playerinfo[i];
                ++count;
                sb.AppendFormat("\"{0}\" ", p.name);
                if (sb.Length > 250 || i == (pi.playerinfo.Length - 1))
                {
                    Debug.LogInfo("Sending a PI Line.");
                    cmd.Reply("({0}): {1} ", count, sb.ToString());
                    sb.Clear();
                    count = 0;
                }
            }
        }
        catch (Exception)
        {
            cmd.Reply("Request failed.");
            //Debug.LogError(e, "Request Failed");
        }

但是,那里没有捕获异常。相反,调试器会中断。有什么建议吗?

【问题讨论】:

    标签: c# exception asynchronous async-await


    【解决方案1】:

    异常会被捕获。只需在调试器中继续。

    【讨论】:

    • 或者在没有调试器的情况下运行。
    • 我正在使用调试器进行压力测试,但是一旦你说我禁用了 ctrl+alt+e 中的异常以通过它:)
    猜你喜欢
    • 1970-01-01
    • 2014-01-30
    • 2014-12-02
    • 2019-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-14
    • 1970-01-01
    相关资源
    最近更新 更多