2014-03-01 207 views
0

我有一個關於在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); }我想的是例外,通過該調用的方法被捕獲等待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"); 
     } 

然而的代碼中,異常沒有被捕獲那裏。相反,調試器會中斷。有什麼建議?

回答

4

異常將被捕獲。只需在調試器中繼續。

+0

或者在沒有調試器的情況下運行。 – svick

+0

我正在使用調試器進行壓力測試,但是一旦您說我禁用了ctrl + alt + e中的異常以便通過它:) – Ben