Task<WebResponse>.Wait lasts forever

天涯浪子 提交于 2019-12-12 18:15:26

问题


C#, .Net 4.5. I have a queue that contains objects which are to be processed. Processing includes obtaining data with the URL which specified in one of the fields of the object. In the course of operation the new objects can be added to the queue. When I tried to do the work with the network asynchronous, I faced with a problem.

Here is a minimum code.

public partial class Form1 : Form
{
    private void button1_Click(object sender, EventArgs e)
    {
        string[] urls = { "http://www.stackoverflow.com/", 
                            "http://www.google.com/", 
                            "http://www.microsoft.com/" };
        int i = 0;
        Queue<MyClass1> queue = new Queue<MyClass1>();

        HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(urls[i]);
        webRequest.Proxy.Credentials = CredentialCache.DefaultCredentials;
        queue.Enqueue(new MyClass1(urls[i], webRequest.GetResponseAsync()));

        while (queue.Count > 0)
        {
            MyClass1 o = queue.Dequeue();
            o.RespTask.Wait();
            Debug.Print("Url: {0}, bytes: {1}", o.Url, 
                o.RespTask.Result.ContentLength);

            i++;
            if (i < urls.Length)
            {
                webRequest = (HttpWebRequest)WebRequest.Create(urls[i]);
                webRequest.Proxy.Credentials = CredentialCache.DefaultCredentials;
                queue.Enqueue(new MyClass1(urls[i], webRequest.GetResponseAsync()));
            }
        } 
    }
}

public class MyClass1
{
    public MyClass1() { }
    public MyClass1(string url, Task<WebResponse> respTask)
    {
        Url = url;
        RespTask = respTask;
    }

    public string Url;
    public Task<WebResponse> RespTask;
}

That code hangs on o.RespTask.Wait(); on third iteration of cycle. Before this call o.RespTask.Status has value WaitingForActivation and waiting lasts forever. What am I doing wrong?

UPDATE. I checked the code on 3 boxes. On two of them (Win7 32-bit and Win7 64-bit) the program hangs. On the third (Win7 64-bit) everything is working fine. It seems to me very strange.


回答1:


This code has ceased to hang after such a modification:

...
Debug.Print("Url: {0}, bytes: {1}", o.Url, 
    o.RespTask.Result.ContentLength);

o.RespTask.Result.Close();

i++;
...

My mistake was that I did not pay attention to the fact that the call to the Close method of the HttpWebResponse class is a must.



来源:https://stackoverflow.com/questions/12525460/taskwebresponse-wait-lasts-forever

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!