1. 程式人生 > >C#使用BeginInvoke和EndInvoke異步下載和獲取返回結果

C#使用BeginInvoke和EndInvoke異步下載和獲取返回結果

href 本地文件 add 多線程下載 線程 esp class .sh 問題:

場景:為了防止UI卡死,使用異步下載文件

問題:采用多線程下載,關閉窗口後下載線程不能停止,線程操作麻煩。

參考:C#客戶端的異步操作: http://www.cnblogs.com/fish-li/archive/2011/10/23/2222013.html

方案:采用BeginInvoke的方式調用下載方法,委托會自動啟動新線程,停止時也不需要手動控制。使用EndInvoke獲取返回結果。

try
{
    IAsyncResult ir = process.BeginInvoke(new HttpDownloadDelegate(HttpDownload),url,path); 
    bool result = process.EndInvoke(ir);
}
catch(Exception ex) { MessageBox.Show(ex.Message); } //方法聲明 public delegate bool HttpDownloadDelegate(string url, string path) public bool HttpDownload(string url, string path) { //下載方法... }

HTTP下載:

/// <summary>
        /// http下載文件
        /// </summary>
        /// <param name="url">
下載文件地址</param> /// <param name="path">文件存放地址,包含文件名</param> /// <returns></returns> public bool HttpDownload(string url, string path) { string tempPath = System.IO.Path.GetDirectoryName(path) + @"\temp"; System.IO.Directory.CreateDirectory(tempPath);
//創建臨時文件目錄 string tempFile = tempPath + @"\" + System.IO.Path.GetFileName(path) + ".temp"; //臨時文件 if (System.IO.File.Exists(tempFile)) { System.IO.File.Delete(tempFile); //存在則刪除 } try { FileStream fs = new FileStream(tempFile, FileMode.Append, FileAccess.Write, FileShare.ReadWrite); // 設置參數 HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; //發送請求並獲取相應回應數據 HttpWebResponse response = request.GetResponse() as HttpWebResponse; //直到request.GetResponse()程序才開始向目標網頁發送Post請求 Stream responseStream = response.GetResponseStream(); //創建本地文件寫入流 //Stream stream = new FileStream(tempFile, FileMode.Create); byte[] bArr = new byte[1024]; int size = 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#使用BeginInvoke和EndInvoke異步下載和獲取返回結果