【发布时间】: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