C#异步编程有四种方式,可参考下面的文章
MSDN-异步编程概述 [C#] 并且在MSDN帮助文档中也有相关介绍
MSDN:ms-help://MS.VSCC.2003/MS.MSDNQTR.2003FEB.2052/cpgenref/html/cpconasynchronousexecution.htm
另外这样也可以实现相同的效果(我还没有使用过):
//System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(DoDownloadWork), null);
下面是一段实际程序的片段(很多属性字段被我省去了):
namespace Hooyee.Ftp {
public class FileDownloader {
public FileDownloader() {
}
IFtpDownloader Members#region IFtpDownloader Members
private delegate void AsyncDownloadDelegate(FileStream fileStream);
public void Start() {
IResult<FileStream> resultStream;
resultStream = (new LocalFileAccess()).AppendFile(_saveAs); //_saveAs是类的一个字段,定义都被省去
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 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 {
//下载完成后修改文件名
LocalFileAccess.Rename(_saveAs);
} catch {
}
if (OnFinished != null) {
FtpNoticeEventArgs e = new FtpNoticeEventArgs(_remoteFile, 0, FtpDownloadActions.Finish);
OnFinished(this, e);
}
}
#endregion
}
}