15
2015
01

.Net中模拟上传文件动态显示进度的事件示例

.Net Code:

    public class UploadEventArgs : EventArgs//作为事件的参数,必须派生自EventArgs基类
    {
        public UploadEventArgs(int percent)
        {
            this.Percent = percent;
        }
        public int Percent { get; set; }
    }
    public class Upload
    {
        public event EventHandler<UploadEventArgs> Uploading;//定义事件,上传中实时通知上传进度
        public int Percent{get;private set;}
        public Upload()
        {
            Percent = 0;
        }
        public void DoUpload()
        {
            UploadEventArgs ev=new UploadEventArgs(0);
            while(Percent<100)
            {
//上传文件代码简单,就不写出了
                System.Threading.Thread.Sleep(1000);
                Percent+=15;
                if (Percent > 100) Percent = 100;
                ev.Percent=Percent;
                Uploading(this, ev);
            }
        }
    }
    public class FileToUpload
    {
        private string fileName;
        public FileToUpload(string filename)
        {
            this.fileName = filename;
        }
        public void GetStatus(object sender, UploadEventArgs e)
        {
            Console.WriteLine("file:{0},UploadPercent:{1}", fileName, e.Percent);
        }
    }
    public class EventTest
    {
        public void test()
        {
            var upload = new Upload();
            var file = new FileToUpload("001.dox");
            upload.Uploading += file.GetStatus;
            upload.DoUpload();
        }
    }


«1»