Scenario: To prevent a UI card from dying, use an asynchronous download file
Problem: Use multi-threaded download, close the window after the download thread can not stop, thread operation trouble.
Reference: Asynchronous operations for C # clients: http://www.cnblogs.com/fish-li/archive/2011/10/23/2222013.html
Scenario: The download method is invoked in a begininvoke manner, the delegate automatically launches a new thread, and does not require manual control when it is stopped. Use EndInvoke to get the returned results.
Try{IAsyncResult IR= Process. BeginInvoke (Newhttpdownloaddelegate (httpdownload), Url,path); BOOLresult =process. EndInvoke (IR);}Catch(Exception ex) {MessageBox.Show (ex). Message);}//Method Declaration Public Delegate BOOLHttpdownloaddelegate (stringUrlstringpath) Public BOOLHttpdownload (stringUrlstringpath) { //Download Method...}
HTTP Download:
/// <summary> ///http Download File/// </summary> /// <param name= "url" >Download file Address</param> /// <param name= "path" >file storage address, including file name</param> /// <returns></returns> Public BOOLHttpdownload (stringUrlstringpath) { stringTempPath = System.IO.Path.GetDirectoryName (Path) +@"\temp"; System.IO.Directory.CreateDirectory (TempPath); //Create a temporary file directory stringTempfile = TempPath +@"\"+ System.IO.Path.GetFileName (Path) +". Temp";//Temporary Files if(System.IO.File.Exists (tempfile)) {System.IO.File.Delete (tempfile); //exists then delete } Try{FileStream fs=NewFileStream (Tempfile, Filemode.append, FileAccess.Write, fileshare.readwrite); //Setting ParametersHttpWebRequest request = webrequest.create (URL) asHttpWebRequest; //send request and get corresponding response dataHttpWebResponse response = Request. GetResponse () asHttpWebResponse; //until request. The GetResponse () program only starts sending a POST request to the destination Web pageStream Responsestream =Response. GetResponseStream (); //creating a local file write stream//Stream stream = new FileStream (tempfile, filemode.create); byte[] BArr =New byte[1024x768]; intSize = Responsestream.read (BARR,0, (int) barr.length); while(Size >0) { //Stream. Write (BARR, 0, size);Fs. Write (BARR,0, size); Size= Responsestream.read (BARR,0, (int) barr.length); } //Stream. Close ();FS. Close (); Responsestream.close (); System.IO.File.Move (tempfile, path); return true; } Catch(Exception ex) {return false; } }
C # asynchronously downloads and gets returned results using BeginInvoke and EndInvoke