C # There are four asynchronous programming methods. refer to the following Article
Msdn-asynchronous programming Overview [C #]
In addition, the msdn help documentation also provides relevant introductions.
Msdn: MS-help: // Ms. vscc.2003/ms. msdnqtr.2003feb. 2052/cpgenref/html/cpconasynchronousexecution.htm
In addition, you can achieve the same effect (I have not used it ):
// System. Threading. threadpool. queueuserworkitem (new system. Threading. waitcallback (dodownloadwork), null );
Below is a piece of practiceProgram(Many attribute fields are saved ):
Namespace Hooyee. FTP {
Public Class Filedownloader {
Public Filedownloader () {
}
Iftpdownloader members # Region Iftpdownloader members
Private Delegate Void Asyncdownloaddelegate (filestream );
Public Void Start () {
Iresult < Filestream > Resultstream;
Resultstream = ( New Localfileaccess (). appendfile (_ saveas ); // _ Saveas is a field of the class and its definition is omitted.
Asyncdownloaddelegate asyncdownloaddlg = New Asyncdownloaddelegate (dodownloadwork );
Iasyncresult ar = Asyncdownloaddlg. begininvoke (resultstream. object, New Asynccallback (downloadfinished), asyncdownloaddlg );
// System. Threading. threadpool. queueuserworkitem (new system. Threading. waitcallback (dodownloadwork), null );
}
Private Void Dodownloadwork (filestream) {
Ftpwebresponse response = Null ;
Stream stream = Null ;
Try {
Response = (Ftpwebresponse) _ request. getresponse ();
Stream = Response. getresponsestream ();
Int Reads = 0 ;
Byte [] Buffer = New Byte [buffer_size];
Binarywriter writer = New Binarywriter (filestream );
While (Reads = Stream. Read (buffer, 0 , Buffer_size )) > 0 ) {
Writer. Write (buffer,0, Reads );
}
} Catch (Ioexception ex) {
//Ftplog log = new ftplog ();
//Log. Write
} Catch (Exception ex) {
} Finally {
If (Stream ! = Null ) Stream. Close ();
If (Filestream ! = Null ) Filestream. Close ();
If (Response ! = Null ) Response. Close ();
}
}
Private Void Downloadfinished (iasyncresult AR) {
Asyncdownloaddelegate dlgt = (Asyncdownloaddelegate) Ar. asyncstate;
Dlgt. endinvoke (AR );
Try {
//Modify the file name after the download is complete.
Localfileaccess. Rename (_ saveas );
} Catch {
}
If (Onfinished ! = Null ) {
Ftpnoticeeventargs E= NewFtpnoticeeventargs (_ remotefile,0, Ftpdownloadactions. Finish );
Onfinished (This, E );
}
}
# Endregion
}
}