Set the idea: acquisition target: http://www.8kmm.com, known list of URLs, apply multithreading (thread) to read the list, get the URL can not be repeated (locking lock). Allow unordered collection!
Multithreaded Core code:
#regionGlobal variables//Thread ListList<thread> threadsllist =NewList<thread>(); //URL listlist<string> uurls =Newlist<string>(); //finished listlist<string> okurls =Newlist<string>(); //number of beautiful pictures successfully obtained Public intImgcount =0;#endregion//take a diagram Start button event Private voidLbtngetwebimgstart_linkclicked (Objectsender, LinkLabelLinkClickedEventArgs e) {lbtngetwebimgstart.enabled=false; Getwebsiteimg (); }//Drawing Stop button event Private voidLbtngetwebimgstop_linkclicked (Objectsender, LinkLabelLinkClickedEventArgs e) { Try { foreach(Thread tinchthreadsllist) { if(t! =NULL) {t.abort (); } } } Catch(Exception ex) {Writelog ("Stop failed:"+Ex. Message); } finally{lbtngetwebimgstart.enabled=true; } } /// <summary> ///Get Picture Main method/// </summary> Private voidgetwebsiteimg () {Try{Imgcount=0; Okurls.clear (); Uurls.clear (); Threadsllist.clear (); //First initialize the above string[] URLs = TxtUrl.Text.Split (New string[] {"\ r \ n"}, Stringsplitoptions.removeemptyentries); Lblc.text=URLs. Length.tostring (CultureInfo.InvariantCulture); Uurls=Newlist<string>(URLs); for(inti =0; I <int. Parse (Numthreadud.text); i++)//Looping Create Threads{Thread T=NewThread (Task); T.name=i.tostring (); T.isbackground=true; Threadsllist.add (t); T.start (); } } Catch(Exception ex) {Writelog (ex). Message); } } Public voidTask () { while(Uurls.count >0) {Lblmsg.text=string. Format ("remaining: {0}, accessed: {1}, current number of threads: {2}", Uurls.count, (Okurls.count +1), Threadsllist.count); stringURL =GetUrl (); if(url = ="") { Break; } Else { if(gethttpimg (URL) = = $)//only state 200 is normal, gethttpimg is my method of encapsulation, get the Web page, and get all the canonical pictures.{okurls.add (URL); Lblinfostart.text= (int. Parse (Lblinfostart.text) +1). ToString (CultureInfo.InvariantCulture); WriteHTML (Txturl.text); if(Lblc.text = = Lblinfostart.text)//determines whether the current quantity is total.{Lblmsg.text="Complete"; } } } } } /// <summary> ///Thread loads lock to prevent multiple threads from removing the first one from the list at the same time/// </summary> /// <returns></returns> Public stringGetUrl () {Lock("GETURL") { if(Uurls.count >0) { stringURL = uurls[0]; Uurls.removeat (0); returnURL; } Else { return ""; } } }
WinForm Collection website Beautiful picture program---multi-threaded article