Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this hanging?

Tags:

c#

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?

like image 406
Michael Blake Avatar asked Nov 12 '22 23:11

Michael Blake


1 Answers

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

like image 58
SLaks Avatar answered Nov 14 '22 23:11

SLaks