C#异步编程(2)

电脑杂谈  发布时间:2019-08-23 15:07:39  来源:网络整理
     CancellationTokenSource cts;
        private async void button3_Click(object sender, EventArgs e)
        {
            progressBar1.Maximum = 100;
            progressBar1.Value = 0;
            cts = new CancellationTokenSource();
            CancellationToken ct = cts.Token;
            var pp = new Progress<int>();
            pp.ProgressChanged += (s, n) => {
                progressBar1.Value = n;
            };
            var tt = Task.Run(()=>MYThreadAsync(pp,cts.Token,500),cts.Token);
            try
            {
                await tt;
                if (tt.Exception == null)
                    listBox1.Items.Add("任务完成");
            }
            catch (Exception ex)
            {
                listBox1.Items.Add("异常" + ex.Message);
            }
        }         
        private void button4_Click(object sender, EventArgs e)
        {
            cts.Cancel();
        }
        public  void MYThreadAsync(IProgress<int> progress, CancellationToken ct, int delay)
        {
            int p = 0;//进度
            while (p < 100 && ct.IsCancellationRequested == false)
            {
                p += 1;
                Thread.Sleep(delay);
                progress.Report(p);//这个方法将会触发ProgressChanged事件更新进度条
            }
        }

6. 定时完成任务

无论是服务器还是客户端,都是有定时完成某个任务的还要的。System.Timers.Timer类是一个不错的定时设定类,这个类可以引起事件,但它默认是程池中引起风波,而不是在当前线程中造成事件。Timer类的常见属性有AutoReset和Interval属性,AutoReset是获得或修改一个bool值,该值为true表示每次间隔结束时都引起一次Elapsed事件,false表示仅在首次间隔结束时引起一次该事件。Interval属性是获得或修改两次Elapsed事件的间隔时间,该值应该高于零并大于Int.MaxValue,默认值为100毫秒。Timer类也有两个常用方式那就是Start和Stop方法。

还有一个System.Threading.Timer类,它也是程池中定时执行任务c 异步编程,它与前一个Timer类的差别是该类不使用事件模型,而是直接借助TimerCallback类型的委托来推动的。该类的构造函数为:Timer(TimerCallback callback,Object state,TimeSpan douTime,TimeSpan period)。callback表示要执行的方式,state表示一个包含回调方法要使用的信息的对象,dueTime是首次调用回调方式之前延迟的时间,period表示每次调用回调方式的时间间隔,-1表示解除。这样创建对象后,首次前往dueTime延时时间会手动调用一次callback委托,以后每隔period时间间隔调用一次。以下是这两种方法的运行效果和源代码。

     System.Timers.Timer timer;
        System.Threading.Timer threadtimer;
        private void button2_Click(object sender, EventArgs e)//Timers.Timer
        {
            progressBar1.Maximum = 100;
            progressBar1.Value = 0;
            int pro=0;
            timer = new System.Timers.Timer(500);
            timer.AutoReset = true;
            timer.Elapsed+= (obj, args) =>
            { 
                pro+=5;
                progressBar1.Value = pro;
            };
            timer.Start();
        }
       private void button5_Click(object sender, EventArgs e)
       {
           timer.Stop();
           listBox1.Items.Add("第一个已经停止");
       }
    //Threading.Timer类
       private void button1_Click(object sender, EventArgs e)
       {
           progressBar2.Maximum = 100;
           progressBar2.Value = 0;
           TimeSpan dueTime = new TimeSpan(0, 0, 0, 1);
           TimeSpan period = new TimeSpan(0, 0, 0, 0, 200);
           System.Threading.TimerCallback timecall = new TimerCallback((obj) => progressBar2.Value += 5);
           threadtimer = new System.Threading.Timer(timecall, null, dueTime, period);
       }
       private void button6_Click(object sender, EventArgs e)
       {
           threadtimer.Dispose();
           listBox1.Items.Add("第二个已经停止");
       }

这篇文章只总结了单个任务的异步执行的基础,还得继续学习多任务并行执行。如果有更好的科技或者与企业使用相关的异步技术,希望园友可以强调我继续学习。


本文来自电脑杂谈,转载请注明本文网址:
https://www.pc-fly.com/a/ruanjian/article-120301-2.html

相关阅读
    发表评论  请自觉遵守互联网相关的政策法规,严禁发布、暴力、反动的言论

    热点图片
    拼命载入中...