Michael Blake
Michael Blake

Reputation: 995

Why is this hanging?

private async void button1_Click(object sender, EventArgs e)
    {
        var cookie = webBrowser1.Document.Cookie;
        await
            Task.WhenAll(
                listBox1
                .Items
                .Cast<string>()
                .Select(async s =>
                {
                    var data = "action=relationship&user_id=" + s + "&relation=follow";
                    var req = WebRequest.Create("http://example.com") as HttpWebRequest;
                    req.Method = "POST";
                    req.ContentType = "application/x-www-form-urlencoded";
                    req.ContentLength = data.Length;
                    req.Headers["cookie"] = cookie;
                    using (var sw = new StreamWriter(await req.GetRequestStreamAsync(), Encoding.ASCII))
                    {
                        sw.Write(data);
                        sw.Close();
                    }
                }));
        listBox1.Items.Clear();
    }

I've tried this a million times, and it runs it two times every time. And when it runs it those two times, it does what it's supposed to.

What it's supposed to do is take items from a listbox, and use each item as part of a POST request. Then when it's done, it clears the listbox.

Can someone explain what's wrong?

Upvotes: 5

Views: 540

Answers (2)

martinh_kentico
martinh_kentico

Reputation: 973

To add to @SLaks

We had the same problem and it turned out to be a problem in different place than one would originally guess.

You need to .Dispose() or at least .Close() the response that you get from .GetResponseAsync, otherwise the next call to .GetRequestStreamAsync hangs.

It seems that the code behind this holds some limited (rather low) amount of sockets or locks, that disallow further requests to even begin until previous request has completed.

Upvotes: 0

SLaks
SLaks

Reputation: 887453

You should call req.GetResponseAsync() to actually send the request.

Upvotes: 1

Related Questions