异步方法中的异常处理

时间:2014-03-01 00:36:11

标签: c# exception asynchronous async-await

我有一个关于在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");
        }

但是,例外情况并没有在那里发现。相反,调试器中断了。有什么建议吗?

1 个答案:

答案 0 :(得分:4)

将捕获异常。继续调试器。