Task.Wait lasts forever

2019-07-15 11:25发布

问题:

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.



标签: c# .net-4.5