欧美大屁股bbbbxxxx,狼人大香伊蕉国产www亚洲,男ji大巴进入女人的视频小说,男人把ji大巴放进女人免费视频,免费情侣作爱视频

歡迎來到入門教程網(wǎng)!

C#教程

當前位置:主頁 > 軟件編程 > C#教程 >

C#實現(xiàn)多線程下載文件的方法

來源:本站原創(chuàng)|時間:2020-01-10|欄目:C#教程|點擊: 次

本文實例講述了C#實現(xiàn)多線程下載文件的方法。分享給大家供大家參考。具體實現(xiàn)方法如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading;
using System.Net;
namespace WfpApp
{
 public class MultiDownload
 {
  #region 變量
  private int _threadNum;    //線程數(shù)量
  private long _fileSize;    //文件大小
  private string _fileUrl;   //文件地址
  private string _fileName;   //文件名
  private string _savePath;   //保存路徑
  private short _threadCompleteNum; //線程完成數(shù)量
  private bool _isComplete;   //是否完成
  private volatile int _downloadSize; //當前下載大小(實時的)
  private Thread[] _thread;   //線程數(shù)組
  private List<string> _tempFiles = new List<string>();
  private object locker = new object();
  #endregion
  #region 屬性
  /// <summary>
  /// 文件名
  /// </summary>
  public string FileName
  {
   get
   {
    return _fileName;
   }
   set
   {
    _fileName = value;
   }
  }
  /// <summary>
  /// 文件大小
  /// </summary>
  public long FileSize
  {
   get
   {
    return _fileSize;
   }
  }
  /// <summary>
  /// 當前下載大小(實時的)
  /// </summary>
  public int DownloadSize
  {
   get
   {
    return _downloadSize;
   }
  }
  /// <summary>
  /// 是否完成
  /// </summary>
  public bool IsComplete
  {
   get
   {
    return _isComplete;
   }
  }
  /// <summary>
  /// 線程數(shù)量
  /// </summary>
  public int ThreadNum
  {
   get
   {
    return _threadNum;
   }
  }
  /// <summary>
  /// 保存路徑
  /// </summary>
  public string SavePath
  {
   get
   {
    return _savePath;
   }
   set
   {
    _savePath = value;
   }
  }
  #endregion
  /// <summary>
  /// 構造函數(shù)
  /// </summary>
  /// <param name="threahNum">線程數(shù)量</param>
  /// <param name="fileUrl">文件Url路徑</param>
  /// <param name="savePath">本地保存路徑</param>
  public MultiDownload(int threahNum, string fileUrl, string savePath)
  {
   this._threadNum = threahNum;
   this._thread = new Thread[threahNum];
   this._fileUrl = fileUrl;
   this._savePath = savePath;
  }
  public void Start()
  {
   HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_fileUrl);
   HttpWebResponse response = (HttpWebResponse)request.GetResponse();
   _fileSize = response.ContentLength;
   int singelNum = (int)(_fileSize / _threadNum);  //平均分配
   int remainder = (int)(_fileSize % _threadNum);  //獲取剩余的
   request.Abort();
   response.Close();
   for (int i = 0; i < _threadNum; i++)
   {
    List<int> range = new List<int>();
    range.Add(i * singelNum);
    if (remainder != 0 && (_threadNum - 1) == i) //剩余的交給最后一個線程
     range.Add(i * singelNum + singelNum + remainder - 1);
    else
     range.Add(i * singelNum + singelNum - 1);
    //下載指定位置的數(shù)據(jù)
    int[] ran = new int[] { range[0], range[1] };
    _thread[i] = new Thread(new ParameterizedThreadStart(Download));
    _thread[i].Name = System.IO.Path.GetFileNameWithoutExtension(_fileUrl) + "_{0}".Replace("{0}", Convert.ToString(i + 1));
    _thread[i].Start(ran);
   }
  }
  private void Download(object obj)
  {
   Stream httpFileStream = null, localFileStram = null;
   try
   {
    int[] ran = obj as int[];
    string tmpFileBlock = System.IO.Path.GetTempPath() + Thread.CurrentThread.Name + ".tmp";
    _tempFiles.Add(tmpFileBlock);
    HttpWebRequest httprequest = (HttpWebRequest)WebRequest.Create(_fileUrl);
    httprequest.AddRange(ran[0], ran[1]);
    HttpWebResponse httpresponse = (HttpWebResponse)httprequest.GetResponse();
    httpFileStream = httpresponse.GetResponseStream();
    localFileStram = new FileStream(tmpFileBlock, FileMode.Create);
    byte[] by = new byte[5000];
    int getByteSize = httpFileStream.Read(by, 0, (int)by.Length); //Read方法將返回讀入by變量中的總字節(jié)數(shù)
    while (getByteSize > 0)
    {
     Thread.Sleep(20);
     lock (locker) _downloadSize += getByteSize;
     localFileStram.Write(by, 0, getByteSize);
     getByteSize = httpFileStream.Read(by, 0, (int)by.Length);
    }
    lock (locker) _threadCompleteNum++;
   }
   catch (Exception ex)
   {
    throw new Exception(ex.Message.ToString());
   }
   finally
   {
    if (httpFileStream != null) httpFileStream.Dispose();
    if (localFileStram != null) localFileStram.Dispose();
   }
   if (_threadCompleteNum == _threadNum)
   {
    Complete();
    _isComplete = true;
   }
  }
  /// <summary>
  /// 下載完成后合并文件塊
  /// </summary>
  private void Complete()
  {
   Stream mergeFile = new FileStream(@_savePath, FileMode.Create);
   BinaryWriter AddWriter = new BinaryWriter(mergeFile);
   foreach (string file in _tempFiles)
   {
    using (FileStream fs = new FileStream(file, FileMode.Open))
    {
     BinaryReader TempReader = new BinaryReader(fs);
     AddWriter.Write(TempReader.ReadBytes((int)fs.Length));
     TempReader.Close();
    }
    File.Delete(file);
   }
   AddWriter.Close();
  }
 }
}

調用:

string httpUrl = @"http://172.28.98.96/fdimsservice/2.rar";
string saveUrl = System.Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "http://" + System.IO.Path.GetFileName(httpUrl);
int threadNumber = 5;
MultiDownload md = new MultiDownload(threadNumber, httpUrl, saveUrl);
md.Start();

希望本文所述對大家的C#程序設計有所幫助。

網(wǎng)頁制作CMS教程網(wǎng)絡編程軟件編程腳本語言數(shù)據(jù)庫服務器

如果侵犯了您的權利,請與我們聯(lián)系,我們將在24小時內進行處理、任何非本站因素導致的法律后果,本站均不負任何責任。

聯(lián)系QQ:835971066 | 郵箱:835971066#qq.com(#換成@)

Copyright © 2002-2020 腳本教程網(wǎng) 版權所有