使用多线程创建下载任务

public class ThreadDownloadFile
{
    //下载地址
    public string url;
    //下载到本地的目录
    public string localPath;
    //检查是否下载完成
    public bool isDone = false;

    public ThreadDownloadFile(string url, string localPath)
    {
        this.url = url;
        this.localPath = localPath;
    }

    //线程的工作方法:下载文件
    public void Download()
    {
        long lastDownPos = 0;
        //检查本地是否已经有该文件,如果有,续传
        FileStream fs;
        if (File.Exists(localPath))
        {
            fs = File.Open(localPath, FileMode.Append);
            lastDownPos = fs.Length;
        }
        else //如果没有,新建
        {
            fs = File.Create(localPath);
        }
        //开启一个线程
        //web请求的处理
        HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;
        //是否断电续传
        if (lastDownPos > 0)
        {
            request.AddRange((int)lastDownPos);//从上一次下载的位置开始读取本次的数据
        }
        //从请求对象得到响应对象,从响应对象取得响应数据
        using (Stream stream = request.GetResponse().GetResponseStream())
        {
            int nReadSize = 0;
            do
            {
                byte[] buffer = new byte[1024 * 100];
                nReadSize = stream.Read(buffer, 0, buffer.Length);
                fs.Write(buffer, 0, nReadSize);
            } while (nReadSize > 0);
        }
        fs.Flush();
        fs.Close();
        isDone = true;
    }
    ThreadDownloadFile downFile = null;
    string localPath;
    public void OnGUI()
    {
        if (GUILayout.Button("Download"))
        {
            string url = "http://xiazai.xiazaiba.com/Soft/F/FSCapture_8.4_XiaZaiBa.zip";
            localPath = Application.persistentDataPath+"/"+Path.GetFileName(url);
            downFile = new ThreadDownloadFile(url, localPath);
            //开启一个线程,做文件下载
            Thread thread = new Thread(downFile.Download);
            //启动线程
            thread.Start();
        }
        if (downFile!=null&&downFile.isDone)
        {
            GUILayout.Label("Complete");
            //print(localPath);
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值