0

I have a test web connection form in c#. I want to show a loading window while my connection is being checked, and then show the result of checking.

This is my code for testing the web connection:

   public bool ConnectionAvailable(string strServer)
   {
        try
        {
            HttpWebRequest reqFP = (HttpWebRequest)HttpWebRequest.Create(strServer);

           HttpWebResponse rspFP = (HttpWebResponse)reqFP.GetResponse();
            if (HttpStatusCode.OK == rspFP.StatusCode)
            {
              // HTTP = 200 - Internet connection available, server online
                rspFP.Close();
                return true;
            }
            else
           {
               // Other status - Server or connection not available
                rspFP.Close();
                return false;
            }
        }
        catch (WebException)
        {
            // Exception - connection not available
            return false;
        }
    }

And this:

    private void button1_Click(object sender, EventArgs e)
    {
        string url = "Web-url";
        label1.Text = "Checking ...";
        button1.Enabled = false;

        if (ConnectionAvailable(url))
        {
            WebClient w = new WebClient();
            w.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
            label1.Text = w.UploadString(url, "post", "SN=" + textBox1.Text);
            button1.Enabled = true;
        }
        else
        {
            label1.Text = "Conntion fail";
            button1.Enabled = true;
        }

    }
4

2 回答 2

0

I am thinking of threading! One thread checks the connection while the other one is showing the loading window. If for example the connection has been established you can notify the other thread and show the result.

于 2013-08-24T06:20:41.807 回答
0

在 Windows 窗体应用程序上,用户界面在一个线程上运行,如果您尝试运行一个长时间运行的进程,检查 Web 连接可能最终会导致窗体冻结,直到它完成工作。

所以,我会启动一个新线程来进行检查。然后引发一个事件以返回结果。在所有这些发生的同时,您可以使用用户界面做您喜欢的事情,例如加载图形,甚至允许用户继续使用不需要互联网连接的功能。

创建您自己的 EventArgs 类,以便您可以传回结果:

public class ConnectionResultEventArgs : EventArgs
{
    public bool Available { get; set; }
}

然后在您的表单类中,创建您的事件、处理程序和事件到达时的操作方法

//Create Event and Handler
    public delegate void ConnectionResultEventHandler(object sender, ConnectionResultEventArgs e);
    public event ConnectionResultEventHandler ConnectionResultEvent;

//Method to run when the event has been receieved, include a delegate in case you try to interact with the UI thread
    delegate void ConnectionResultDelegate(object sender, ConnectionResultEventArgs e);
    void ConnectionResultReceived(object sender, ConnectionResultEventArgs e)
    {
        //Check if the request has come from a seperate thread, if so this will raise an exception unless you invoke.
        if (InvokeRequired)
        {
            BeginInvoke(new ConnectionResultDelegate(ConnectionResultReceived), new object[] { this, e });
            return;
        }

        //Do Stuff
        if (e.Available)
        {
            label1.Text = "Connection Good!";
            return;
        }

        label1.Text = "Connection Bad";
    }

在表单加载时订阅事件:

private void Form1_Load(object sender, EventArgs e)
    {
        //Subscribe to the the results event.
        ConnectionResultEvent += ConnectionResultReceived;
    }

然后设置工作线程:

//Check the connection
    void BeginCheck()
    {
        try
        {
            HttpWebRequest reqFP = (HttpWebRequest)HttpWebRequest.Create("http://google.co.uk");

            HttpWebResponse rspFP = (HttpWebResponse)reqFP.GetResponse();
            if (HttpStatusCode.OK == rspFP.StatusCode)
            {
                // HTTP = 200 - Internet connection available, server online
                rspFP.Close();

                ConnectionResultEvent(this, new ConnectionResultEventArgs {Available = true});
            }
            else
            {
                // Other status - Server or connection not available
                rspFP.Close();

                ConnectionResultEvent(this, new ConnectionResultEventArgs { Available = false });
            }
        }
        catch (WebException)
        {

            // Exception - connection not available
            //Raise the Event - Connection False
            ConnectionResultEvent(this, new ConnectionResultEventArgs { Available = false });
        }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        //loading graphic, screen or whatever
        label1.Text = "Checking Connection...";

        //Begin the checks - Start this in a new thread
        Thread t = new Thread(BeginCheck);
        t.Start();
    }
于 2013-08-24T06:56:14.263 回答