Support of progress reporting and incremental results in .NET 4.0 “Task Parallel Library”

后端 未结 5 633
有刺的猬
有刺的猬 2020-12-29 07:49

I know that Task Parallel Library is still in Beta and there are likely to be less resources available but from whatever I have read, library gives very special treatment to

5条回答
  •  一向
    一向 (楼主)
    2020-12-29 08:54

    This example updates a progress bar:

    using System;   
    using System.Threading;   
    using System.Threading.Tasks;   
    using System.Windows.Forms;   
    
    class SimpleProgressBar : Form   
    {   
        [STAThread]   
        static void Main(string[] args)   
        {   
            Application.EnableVisualStyles();   
            Application.Run(new SimpleProgressBar());   
        }   
    
        protected override void OnLoad(EventArgs e)   
        {   
            base.OnLoad(e);   
    
            int iterations = 100;   
    
            ProgressBar pb = new ProgressBar();   
            pb.Maximum = iterations;   
            pb.Dock = DockStyle.Fill;   
            Controls.Add(pb);   
    
            Task.ContinueWith(delegate   
            {   
                Parallel.For(0, iterations, i =>  
                {   
                    Thread.SpinWait(50000000); // do work here   
                    BeginInvoke((Action)delegate { pb.Value++; });   
                });   
            });   
        }   
    }  
    

    Updating a progress bar from inside a Parallel.For

提交回复
热议问题