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); } } } }
posted on 2014-01-07 16:46 Goodspeed 阅读(3286) 评论(0) 编辑 收藏 举报