private async Task<string> Request(url) { Task<string> task = null; try { task = MakeAsyncRequest(url,"text/HTML"); return await task; } catch { return null; } } private async Task<string> MakeAsyncRequest(string url,string ContentType) { httpWebRequest request = (httpWebRequest)WebRequest.Create(url); request.ContentType = ContentType; request.Method = WebRequestMethods.http.Get; request.Timeout = 20000; request.Proxy = null; Task<WebResponse> task = Task.Factory.FromAsync( request.BeginGetResponse,asyncResult => request.EndGetResponse(asyncResult),(object)null); //issue here: return await task.ContinueWith(t => ReadStreamFromresponse(t.Result)); }private string ReadStreamFromresponse(WebResponse response) { using (Stream responseStream = response.GetResponseStream()) using (StreamReader sr = new StreamReader(responseStream)) { //Need to return this response string strContent = sr.ReadToEnd(); return strContent; } }
我在foreach循环中调用Request(url)
foreach(var url in myUrlList){ string body = Request(method).Result;}
但由于某种原因,代码在返回时堆叠等待task.ContinueWith(t => ReadStreamFromresponse(t.Result));只是冷冻.
有没有更好的方法来做到这一点,或者有人可以解释发生了什么?
我没有得到任何错误只是等待的问题……
Result
in your foreach
loop is causing a deadlock,正如我在博客上解释的那样.总之,await将捕获“上下文”(例如,UI上下文),并使用它来恢复异步方法.一些上下文(例如,UI上下文)仅允许上下文中的一个线程.因此,如果通过调用Result来阻止该特殊线程(例如,UI线程),则异步方法无法在该上下文中继续执行. 所以,解决方案是改变你的foreach循环:
foreach(var url in myUrlList){ string body = await ProcessAsync(method);}
其他说明:
任务返回方法应以“异步”结束,以遵循TAP guidelines.
Task.Factory.FromAsync是不必要的; httpWebRequest已经有了等待的方法.更好的选择是使用httpClIEnt.
我建议你不要使用Task.ContinueWith(或Task.Result,或Task.Wait);请改用.
通过这些简化:
private async Task<string> MakeAsyncRequestAsync(string url,string ContentType){ httpWebRequest request = (httpWebRequest)WebRequest.Create(url); request.ContentType = ContentType; request.Method = WebRequestMethods.http.Get; request.Timeout = 20000; request.Proxy = null; WebResponse response = await request.GetResponseAsync(); return ReadStreamFromresponse(response);}
如果将httpWebRequest更改为httpClIEnt,则可以进一步简化此代码.
总结以上是内存溢出为你收集整理的c# – 如何使HttpWebRequest异步全部内容,希望文章能够帮你解决c# – 如何使HttpWebRequest异步所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)