Backgroundworker is used and executed in the backgroundProgramIt is easier and safer than opening a new thread.
Easy to use
System. componentmodel. backgroundworker BW = new system. componentmodel. backgroundworker ();
// Define what needs to be done in the Child thread
Bw. dowork + = new system. componentmodel. doworkeventhandler (bw_dowork );
// Define what needs to be done after execution
Bw. runworkercompleted + = new system. componentmodel. runworkercompletedeventhandler (bw_runworkercompleted );
// Start executing BW. runworkerasync ();
Static void bw_runworkercompleted (Object sender, system. componentmodel. runworkercompletedeventargs E)
{
MessageBox. Show ("complete" + thread. currentthread. managedthreadid. tostring ());
}
Static void bw_dowork (Object sender, system. componentmodel. doworkeventargs E)
{
MessageBox. Show (thread. currentthread. managedthreadid );
}
I have rewritten a method for processing the notification page. If no result is required, the main program will proceed with the process to ensure efficiency.
/// <Summary>
/// Access the webpage (in asynchronous mode). You only need to activate the webpage and do not need the result
/// </Summary>
/// <Param name = "url"> webpage address </param>
/// <Returns> </returns>
Public static void notify (string URL)
{
Backgroundworker BW = new backgroundworker (); // defines a background object.
// Define what needs to be done in the Child thread
Bw. dowork + = new system. componentmodel. doworkeventhandler (bw_dowork );
Bw. runworkerasync (URL );
}
/// <Summary>
/// Run in the background: Open the webpage
/// </Summary>
/// <Param name = "sender"> </param>
/// <Param name = "E"> </param>
Static void bw_dowork (Object sender, system. componentmodel. doworkeventargs E)
{
String url = (string) E. argument;
Httpwebrequest request = (httpwebrequest) webrequest. Create (URL );
String content = "";
Try
{
Httpwebresponse response = (httpwebresponse) request. getresponse ();
If (response. statuscode = httpstatuscode. OK) // prevents no response
{
Streamreader reader = new streamreader (response. getresponsestream (), system. Text. encoding. getencoding ("gb2312 "));
Content = reader. readtoend ();
Reader. Close ();
}
Log4net. logmanager. getlogger (system. reflection. methodbase. getcurrentmethod (). declaringtype ). debug ("Open Web page asynchronously:" + URL + ", return length:" + content. length. tostring ());
}
Catch (exception ex)
{
Log4net. logmanager. getlogger (system. reflection. methodbase. getcurrentmethod (). declaringtype ). error ("[notify] Open webpage" + URL + "error:" + ex. message );
}
}
The execution is good. This is the tracking situation:
We can see that if multiple accesses occur at the same time, the system will allocate different threads for execution (the preceding thread number ).