尝试Catch Async WebRequest Put

时间:2015-09-16 11:56:17

标签: c# asynchronous async-await webrequest

我遇到了一些问题,试图让这个代码尝试捕获...我试过尝试catch在几个地方,比如在编码之前,在写之前的await内,在flush之前但没有运气什么所以......

var encoder = new ASCIIEncoding();
var data = encoder.GetBytes(limitBody);
req.ContentLength = data.Length;

    await req.GetRequestStreamAsync().ContinueWith(trs =>
    {
        trs.Result.Write(data, 0, data.Length);
        trs.Result.Flush();

        Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)delegate
        {
            Methods.ReadStreamFromResponse(req.GetResponse(), requestUri, siteCode, correlationtoken, "PUT",
                    txtLimitsResponse, null, limitBody, _userId);
        });
   });

每当远程服务器返回错误:(400)错误请求。

应用程序中断,如何捕获此错误并将其输出给用户?

非常感谢

1 个答案:

答案 0 :(得分:1)

您应该只能将try/catch放在await周围。它已经将方法的其余部分注册为延续,因此您不需要ContinueWith,如果您从UI线程调用此方法,则不需要Dispatcher.Invoke作为await存储当前SynchornizationContext并在await之后恢复它。因此,该方法的其余部分也将在UI线程上运行。

var encoder = new ASCIIEncoding();
var data = encoder.GetBytes(limitBody);
req.ContentLength = data.Length;

try
{  
    var result = await req.GetRequestStreamAsync(); 
    result.Write(data, 0, data.Length);
    result.Flush();

    Methods.ReadStreamFromResponse(req.GetResponse(), requestUri, siteCode, correlationtoken, "PUT",
                    txtLimitsResponse, null, limitBody, _userId);      
}
catch(...)
{ 
   ....
}