KjayCopper
KjayCopper

Reputation: 27

Why form.exe freezes after clicking button 3 times?

I launch the C# Form (Via EXE file) on the form I have a button which executes a URL with perimeters (without opening a browser) if the button is clicked more than 3 times (can be at any time) it just completely freezes the program

How can I stop this from happening?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            ASCIIEncoding encoding = new ASCIIEncoding();
            string postData = "apiID=2794187564564";

            // Prepare web request...
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(
                "http://fms.psrpc.co.uk/apistate2.php?" + postData);

            // Send the data.
            myRequest.GetResponse();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.TopMost = true;
            this.FormBorderStyle = FormBorderStyle.None;
            this.WindowState = FormWindowState.Maximized;
        }
    }
}

Upvotes: 0

Views: 60

Answers (1)

Al Kepp
Al Kepp

Reputation: 5980

Don't forget to call Dispose on all IDisposable types. Although it is not clearly visible here, this applies also to the result of GetResponse.

// Send the data
myRequest.GetResponse().Dispose();

Also note that you should put it inside try-catch-finally because GetResponse throws an exception when that http server returns something different than 2xx OK return codes.

Upvotes: 1

Related Questions