c# – 从任务中的异步HttpWebRequest调用捕获异常
发布时间:2020-12-15 04:14:46 所属栏目:百科 来源:网络整理
导读:我如何在下面的方法中捕获异常? private static Taskstring MakeAsyncRequest(string url) { if (!url.Contains("http")) url = "http://" + url; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.UserAgent = "Mozilla/4.0 (co
我如何在下面的方法中捕获异常?
private static Task<string> MakeAsyncRequest(string url) { if (!url.Contains("http")) url = "http://" + url; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"; request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; request.Method = "GET"; request.KeepAlive = false; request.ProtocolVersion = HttpVersion.Version10; Task<WebResponse> task = Task.Factory.FromAsync( request.BeginGetResponse,asyncResult => request.EndGetResponse(asyncResult),(object)null); return task.ContinueWith(t => FinishWebRequest(t.Result)); } 我得到404,403等错误的具体地点是: Task<WebResponse> task = Task.Factory.FromAsync( request.BeginGetResponse,(object)null); 我无法弄清楚如何处理它们 解决方法
您的错误可能发生在您的委托调用request.EndGetResponse(asyncResult)中.
但是您可以使用以下命令创建任务: Task<WebResponse> task = Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse,request.EndGetResponse,null); 这应该传播任务的任何例外. 您可以在ContinueWith委托中检查错误: return task.ContinueWith(t => { if (t.IsFaulted) { //handle error Exception firstException = t.Exception.InnerExceptions.First(); } else { return FinishWebRequest(t.Result); } }); 或者,如果您使用的是C#5,则可以使用async / await创建MakeAsyncRequest.这将为您从AggregateException中解除异常: private static async Task<string> MakeAsyncRequest(string url) { if (!url.Contains("http")) url = "http://" + url; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"; request.Accept = "text/html,*/*;q=0.8"; request.Method = "GET"; request.KeepAlive = false; request.ProtocolVersion = HttpVersion.Version10; Task<WebResponse> task = Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse,null); WebResponse response = await task; return FinishWebRequest(response); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- ruby-on-rails – 由于utf8 =?使用元搜索,导致表单错误
- 使用WinRar将Qt编译生成的exe和依赖的dll文件打包为一个exe
- 【低耦合集成TabBarController】最低只需传两个数组即可完成
- objective-c – 如何抑制LLVM自动合成警告?
- 如何做一个随机数在arc4random_uniform()之间的范围?
- u-boot移植--2、EN29LV160AB Nor Flash移植
- c – 为什么’ifstream’和’ofstream’添加到“std”,而’
- c – 为什么Google Test会出现分段错误?
- C_C++变量命名规则
- Vue.set()动态的新增与修改数据,触发视图更新的方法