WebClient的异步处理


using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    public class Download
    {
        object LockObject = new object();

        public static void Main(string[] args)
        {
            var url = "http://mirrors.sohu.com/mysql/MySQL-6.0/MySQL-client-community-6.0.11-0.sles10.i586.rpm";

            new Download().Run(url);
        }

        void Run(string url)
        {
            var wc = new WebClient();

            wc.DownloadProgressChanged += (sender, e) =>
            {
                if (Monitor.IsEntered(LockObject))
                {
                    return;
                }
                Monitor.Enter(LockObject);
                var left = Console.CursorLeft;
                for (int i = 0; i < left; i++)
                {
                    Console.Write('\b');
                }

                var display = e.BytesReceived.ToString() + "/" + e.TotalBytesToReceive.ToString() + "\t" + e.ProgressPercentage + "%";

                Console.Write(display);
                Monitor.Exit(LockObject);
            };

            wc.DownloadDataCompleted += (object sender, DownloadDataCompletedEventArgs e) =>
            {
                Console.WriteLine();
                Console.WriteLine("Finish");
            };
            Console.WriteLine("Start");
            wc.DownloadDataAsync(new Uri(url));
            while (wc.IsBusy)
            {
                Thread.Sleep(1000);
            }
            
        }
    }
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM