Reputation: 2917
I have a question regarding catching exceptions after a long await chain in 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(); }
}
When an exception is raised at new DataContractJsonSerializer(msg.GetType()).WriteObject(_writer.BaseStream, msg); }
I'd like that exception to be caught by the method which calls await SendMessageForResponse, such as the code below
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");
}
However, the exception is not caught there. Instead, the debugger breaks. Any advice?
Upvotes: 0
Views: 172
Reputation: 456427
The exception will be caught. Just continue in the debugger.
Upvotes: 4