Use backgroundworker to detect network connections

Source: Internet
Author: User

[It168]Today's desktop programs are not as independent from the network as they used to, and all kinds of functions are inseparable from Internet connections. Programs often need Internet connections to perform operations such as automatic updates and WebService calls to access remote data. However, before actually accessing remote data, we 'd better ensure that the remote connection is available, in this way, the process and robustness of the program can be circled. It is very time-consuming to dynamically detect Internet connections through programming. If multithreading is not used, the program interface will be deadlocked during detection, and all operations on the main thread will be occupied by the detection connection, frequent deadlocks on the main interface are not a good user experience when detecting whether remote connections are available. In this article, we will create a C # component to solve this problem. The main goal is to create a standard framework for remote connection testing. Such testing must be multi-threaded and executed in the background, after the connection detection is successful, the main thread must be notified to respond to the available connection situations, such as opening a webpage, starting automatic updates, and starting to call WebService.

Before starting, we need to list the technologies required for this project.
1. our component should inherit from component, because it does not need to look like a control and visualized operations, we only need to detect Internet connections in the background, and pass the test results to the main thread in the form of events. And this component should be reusable in any. Net project.
2. We should not only check whether the Internet connection is available, but also whether the specified remote connection is available, for example, whether the specified WebService is available. This requires that we cannot simply use WIN32API or WMI to check the running status of the NIC or ADSL to express the Internet connection.
3. multi-threaded background detection connections are required. We recommend that you use backgroundworker.
4. After the detection is completed, the main thread must be notified to perform corresponding operations. Non-event operations between threads are the same.
5. the main interface should make a visual response to different connection States, which must also be completed by using events.

We have adopted a different method to detect Internet connections. As you can imagine, when any client program needs to connect to the Internet, there must be an address that contains only one IP address, domain name, and port data, through this address, the client program establishes a connection with the remote host for data exchange. Then our customer program will directly check whether the address is available or not to determine whether the Internet connection is available. If the address is available, it will prove that the Internet connection is also available. If the address is unavailable, it will prove two points: 1. The address is invalid; 2. The Internet connection is unavailable. However, the possibility of invalid addresses is very small. First, programmers cannot provide an Invalid Address to allow the client program to try the connection, and there is no possibility of server paralysis, such as attempting to connect www.microsoft.com or www.google.cn.
 

Now, let's start creating our detection component.

First, create a Windows form application and add a component. These processes are not described in detail. We name the newly created component internetconnection. First, we define two private fields: backgroundworker-type bgworker and string-type reliableurl. Then define two attributes:
 

Public String reliableurl
{
Get {return reliableurl ;}
Set {reliableurl = value ;}
}

Public bool active
{
Set
{
If (value = true)
{
Bgworker. runworkerasync ();
}
Else
{
Bgworker. cancelasync ();
}
}
}

The reliableurl attribute is our aforementioned remote address. We can indirectly check whether the Internet connection is available by accessing a reliable address or our own WebService address. The active attribute allows you to control the asynchronous execution status of backgroundworker. You can set the active attribute of this component to true to enable Internet connection detection in the background.

Next we need to define the event. For simplicity, we have defined two events for this component: connected and connectfailure. The former is the event triggered after successful connection, and the latter is the event triggered by failed connection. We do not need to pass parameters for events. For more information about events, see another blog post:. Net events and delegation.

Public event eventhandler connected;
Public event eventhandler connectfailure;

Protected virtual void onconnected (eventargs E)
{
If (connected! = NULL)
{
Connected (this, e );
}
}

Protected virtual void onconnectfailure (eventargs E)
{
If (connectfailure! = NULL)
{
Connectfailure (this, e );
}
}

 

Then, we create the connection detection code. For more information about how to use backgroundworker, see msdn or another blog article: practice. net multithreading (3) and practice. net multithreading (4)
 

Private void backgroundworker_dowork (Object sender, doworkeventargs E)
{
Try
{
Httpwebrequest request = (httpwebrequest) httpwebrequest. Create (reliableurl );
Httpwebresponse response = (httpwebresponse) request. getresponse ();
If (httpstatuscode. OK = response. statuscode)
{
Response. Close ();
E. Result = true;
}
Else
{
E. Result = false;
}
}
Catch (webexception)
{
E. Result = false;
}
}

Private void backgroundworker_runworkercompleted (Object sender, runworkercompletedeventargs E)
{
If (E. Error! = NULL)
{
Throw E. error;
}
Else
{
If (bool) E. Result) // online
{
Onconnected (E );
}
Else // offline
{
Onconnectfailure (E );
}
}
}

Finally, instantiate related private fields in the component initialization method.

Public internetconnection (icontainer container)
{
Container. Add (this );
Initializecomponent ();
Bgworker = new backgroundworker ();
Bgworker. workerreportsprogress = false;
Bgworker. workersuppscanscancellation = false;
Bgworker. dowork + = new doworkeventhandler (this. backgroundworker_dowork );
Bgworker. runworkercompleted + = new runworkercompletedeventhandler (this. backgroundworker_runworkercompleted );
}

After the component is created, compile the entire solution and open the form form1 of the originally created Project windowsformsapplication1. We will find the newly created internetconnection component in the toolbox of vs IDE, drag it to the form1 form and internetconnection1 is available. Put a button, a webbrowser, and a statusstrip on the form, and add a statuslabel to statusstrip. We use webbrowser to display a specific webpage to indicate that the Internet connection is available.

When internetconnection1 is selected, we will find that two events are published. we add the corresponding processing code for these two events:

Private void internetconnection1_connected (Object sender, eventargs E)
{
Toolstripstatuslabel1.image = properties. Resources. online;
Toolstripstatuslabel1.text = "connected to the Internet. The it168.com webpage is being opened ....";
Webbrowser1.navigate ("http://www.it168.com /");
}

Private void internetconnection1_connectfailure (Object sender, eventargs E)
{
Toolstripstatuslabel1.image = properties. Resources. offline;
Toolstripstatuslabel1.text = "not connected to Internet ";
Webbrowser1.navigate (application. startuppath + "\ error.html ");
}

After the connection is successful, a remote webpage is displayed. If the connection fails, a custom HTML file is displayed. For example:

Add code to the documentcompleted event of webbrowser to respond to webpage loading completion:

Private void webbrowserappsdocumentcompleted (Object sender, webbrowserdocumentcompletedeventargs E)
{
Toolstripstatuslabel1.text = "finished ";
}

Finally, add the start test connection code in the Click Event of the button:

Private void button#click (Object sender, eventargs E)
{
Internetconnection1.reliableurl = "http://www.google.cn"; // network connection to be detected
Internetconnection1.active = true;
Toolstripstatuslabel1.image = properties. Resources. Searching;
Toolstripstatuslabel1.text = "trying to connect to the remote server ....";
}

So far, a custom Internet connection component has been created. The program is successfully compiled and debugged in the Windows SP3 + Visual Studio 2008 SP1 environment.
 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.