C # Use semaphore to manage asynchronous download requests
This example describes how C # uses semaphore to manage asynchronous download requests. Share it with you for your reference. The specific implementation method is as follows:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
Var semaphor = new Semaphore (50, 50 ); // We allow at most 50 threads for crawling Var resultPins = new List <Pin> (); // Results stored here Foreach (var pin in new HashSet <string> (pinIdList )) { Semaphor. WaitOne (); Console. Write ("> "); Var pinClient = new WebClient (); PinClient. DownloadStringCompleted + = (sender, ex) => { Var html = ex. Result. Replace ("\ n ",""); PinClient. Dispose (); Lock (pinIdList) { // Do some post-processing and write back the results } Console. Write ("<"); Semaphor. Release (); }; PinClient. DownloadStringAsync (new Uri (string. Format ("http://pinterest.com/pin/%0%/", pin ))); } For (int I = 0; I <50; I ++) semaphor. WaitOne (); // Wait until the last thread ends. Semaphor. Dispose (); Console. WriteLine (); |
I hope this article will help you with C # programming.