danil
danil

Reputation: 3

WPF app is freezing when click on button

I try to send login and password From TEXT filds to Web server via POST method

When I click on button my WPF application freezed.

After 2-5 sec the app has been unfreezing and I can do something in app.

Help me to change my code that will not frozen app. Thanks!

This is code

 var request = (HttpWebRequest)WebRequest.Create("http://www.lololo.net/lolo");
    var postData = "login=" + loginPost;
    postData += "&password=" + passwordPost;
    var data = Encoding.ASCII.GetBytes(postData);
    request.Method = "POST";
    request.ContentType = "application/x-www-form-urlencoded";
    request.ContentLength = data.Length;

    using (var stream = request.GetRequestStream())
    {
        stream.Write(data, 0, data.Length);

    }
    var response = (HttpWebResponse)request.GetResponse();
    responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

Upvotes: 0

Views: 364

Answers (1)

John
John

Reputation: 3702

Your GUI won't be blocked any more if you call the webserver async. Use this code to try: (instead of request.GetResponse)

        request.BeginGetResponse((ar) =>
        {
            var response = (HttpWebResponse)request.EndGetResponse(ar);
            responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

            // do something with the string
        }, null);

Upvotes: 1

Related Questions