日期:2014-05-18 浏览次数:21629 次
 System.IO.Stream ns;
            FileStream fs;
            ns = null;
            byte[] nbytes;//接收缓冲区
            int nreadsize;//接收字节数
            ns = null;
            nbytes = new byte[512];
            nreadsize = 0;
            //("线程" + taskIndex.ToString() + "开始接收");-----------------------------------------关注每个任务线程开始
            fs = new FileStream(httpLoadFile.TaskFileList[taskIndex], System.IO.FileMode.Create);
            //try
            //{
                request = (HttpWebRequest)WebRequest.Create( httpLoadFile.SourceUrl );
                //接收的起始位置及接收的长度 
                request.AddRange( httpLoadFile.TaskStartList[taskIndex] , httpLoadFile.TaskStartList[taskIndex] + httpLoadFile.TaskSizeList[taskIndex] );
                ns = request.GetResponse( ).GetResponseStream( );//获得接收流
                nreadsize = ns.Read( nbytes , 0 , 512 );
                while ( nreadsize > 0 )
                {
                    fs.Write( nbytes , 0 , nreadsize );
                    nreadsize = ns.Read( nbytes , 0 , 512 );
                    //("线程" + taskIndex.ToString() + "正在接收");----------------------------------关注每个任务线程进行
                }
                fs.Close( );
                ns.Close( );
        private double[] readBytes = new double[5];
        private double oldsum = 0;
        private long timegones = 0;
        private Random ran = new Random();
        private SimulateSpeed()
        {
            DispatcherTimer timer = new DispatcherTimer();
            timer.Tick += new EventHandler(timer_Tick);
            timer.Interval = TimeSpan.FromSeconds(1);
            timer.Start();
           
            //这里用了多个线程,最好用ThreadPool
            Thread thread1 = new Thread(new ParameterizedThreadStart(Process));
            thread1.Start(0);
            Thread thread2 = new Thread(new ParameterizedThreadStart(Process));
            thread2.Start(1);
            Thread thread3 = new Thread(new ParameterizedThreadStart(Process));
            thread3.Start(2);
            Thread thread4 = new Thread(new ParameterizedThreadStart(Process));
            thread4.Start(3);
            Thread thread5 = new Thread(new ParameterizedThreadStart(Process));
            thread5.Start(4);
        }
        void timer_Tick(object sender, EventArgs e)
        {
            timegones++;  //计时器走过的时间
            double sum = readBytes.Sum();
            //double speed=sum/timegones;  //下载速度=sum(readBytes)/计时器走过的时间
            double speed = sum -oldsum;    //下载速度=sum(readBytes)-上一秒的字节总和
            oldsum = sum;
            textshow.Text = string.Format("当前速度:{0}kb/s", Math.Round(speed,2).ToString());
        }
        void Process(object obj)
        {