zoukankan      html  css  js  c++  java
  • BackgroundWorker 组件

    代码:

     static void Main(string[] args)
            {
                BackgroundWorker bw = new BackgroundWorker();
                bw.WorkerReportsProgress = true;
                bw.WorkerSupportsCancellation = true;
                bw.DoWork += Worker_doWork;
                bw.ProgressChanged += Worker_ProcessChanged;
                bw.RunWorkerCompleted += Worker_Completed;
                bw.RunWorkerAsync();
                Console.WriteLine("Press C to Cancel");
                do
                {
                    if (Console.ReadKey(true).KeyChar == 'C')
                    {
                        bw.CancelAsync();
                    }
                }
                while (bw.IsBusy);
            }
    
            static void Worker_doWork(object sender, DoWorkEventArgs e)
            {
                Console.WriteLine("当前线程ID:{0}", Thread.CurrentThread.ManagedThreadId);
                BackgroundWorker bw = (BackgroundWorker)sender;
                for (int i = 1; i <= 100; i++)
                {
                    if (bw.CancellationPending == true)
                    {
                        e.Cancel = true;
                        return;
                    }
                    if (i % 10 == 0)
                    {
                        bw.ReportProgress(i);
                    }
                    Thread.Sleep(TimeSpan.FromSeconds(0.1));
                }
                e.Result = 42;
            }
    
            static void Worker_ProcessChanged(object sender, ProgressChangedEventArgs e)
            {
                Console.WriteLine("%{0} is Completed. process thread pool thread id {1}", e.ProgressPercentage, Thread.CurrentThread.ManagedThreadId);
            }
            static void Worker_Completed(object sender, RunWorkerCompletedEventArgs e)
            {
                Console.WriteLine("完成的线程ID:{0}",Thread.CurrentThread.ManagedThreadId);
                if (e.Error != null)
                {
                    Console.WriteLine(e.Error.Message);
                }
                else if (e.Cancelled)
                {
                    Console.WriteLine("Operation has been canceled");
                }
                else
                {
                    Console.WriteLine("The Answer is {0}:",e.Result);
                }
            }
    View Code

    运行结果:

  • 相关阅读:
    ptunnel-简易使用
    socat-简易使用
    ncat-相关参数用法
    通过iodine简单实现dns隧道技术
    HTB-靶机-Safe
    HTB-靶机-Rope
    【mysql子查询&组合查询 05】
    【mysql 库表操作 07】
    【mysql插入&修改&删除 06】
    【mysql 连接查询 04】
  • 原文地址:https://www.cnblogs.com/sportdog/p/9548351.html
Copyright © 2011-2022 走看看