Background Worker Pattern

ContractedBlock.gifExpandedBlockStart.gif代码
  1None.gifusing System;
  2None.gifusing System.Threading;
  3None.gifusing System.ComponentModel;
  4None.gifusing System.Text;
  5None.gif
  6None.gifpublic class PiCalculator
  7ExpandedBlockStart.gifContractedBlock.gifdot.gif{
  8InBlock.gif    public static BackgroundWorker calculationWorker = new BackgroundWorker();
  9InBlock.gif    public static AutoResetEvent resetEvent = new AutoResetEvent(false);
 10InBlock.gif
 11InBlock.gif    public static void Main()
 12ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
 13InBlock.gif        int digitCount;
 14InBlock.gif
 15InBlock.gif        Console.Write("Enter the number of digits to calculate:");
 16InBlock.gif
 17InBlock.gif        if (int.TryParse(Console.ReadLine(), out digitCount))
 18ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
 19InBlock.gif            Console.WriteLine("ENTER to cancel");
 20InBlock.gif            // C# 2.0 Syntax for registering delegates
 21InBlock.gif            calculationWorker.DoWork += CalculatePi;
 22InBlock.gif            // Register the ProgressChanged callback           
 23InBlock.gif            calculationWorker.ProgressChanged +=
 24InBlock.gif                 UpdateDisplayWithMoreDigits;
 25InBlock.gif            calculationWorker.WorkerReportsProgress = true;
 26InBlock.gif            // Register a callback for when the                
 27InBlock.gif            // calculation completes                           
 28InBlock.gif            calculationWorker.RunWorkerCompleted +=
 29InBlock.gif                   new RunWorkerCompletedEventHandler(Complete);
 30InBlock.gif            calculationWorker.WorkerSupportsCancellation = true;
 31InBlock.gif
 32InBlock.gif            // Begin calculating pi for up to digitCount digits
 33InBlock.gif            calculationWorker.RunWorkerAsync(digitCount);
 34InBlock.gif
 35InBlock.gif            Console.ReadLine();
 36InBlock.gif            // If cancel is called after the calculation       
 37InBlock.gif            // has completed it doesn't matter.                
 38InBlock.gif            calculationWorker.CancelAsync();
 39InBlock.gif            // Wait for Complete() to run.                     
 40InBlock.gif            resetEvent.WaitOne();
 41ExpandedSubBlockEnd.gif        }

 42InBlock.gif        else
 43ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
 44InBlock.gif            Console.WriteLine(
 45InBlock.gif                    "The value entered is an invalid integer.");
 46ExpandedSubBlockEnd.gif        }

 47ExpandedSubBlockEnd.gif    }

 48InBlock.gif
 49InBlock.gif    private static void CalculatePi(object sender, DoWorkEventArgs eventArgs)
 50ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
 51InBlock.gif        int digits = (int)eventArgs.Argument;
 52InBlock.gif
 53InBlock.gif        StringBuilder pi = new StringBuilder("3.", digits + 2);
 54InBlock.gif        calculationWorker.ReportProgress(0, pi.ToString());
 55InBlock.gif
 56InBlock.gif        // Calculate rest of pi, if required
 57InBlock.gif        if (digits > 0)
 58ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
 59InBlock.gif            for (int i = 0; i < digits; i += 9)
 60ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
 61InBlock.gif
 62InBlock.gif
 63InBlock.gif                // Calculate next i decimal places
 64InBlock.gif                int nextDigit = PiDigitCalculator.StartingAt(
 65InBlock.gif                      i + 1);
 66InBlock.gif                int digitCount = Math.Min(digits - i, 9);
 67InBlock.gif                string ds = string.Format("{0:D9}", nextDigit);
 68InBlock.gif                pi.Append(ds.Substring(0, digitCount));
 69InBlock.gif
 70InBlock.gif                // Show current progress
 71InBlock.gif                calculationWorker.ReportProgress(
 72InBlock.gif                       0, ds.Substring(0, digitCount));
 73InBlock.gif
 74InBlock.gif                // Check for cancellation
 75InBlock.gif                if (calculationWorker.CancellationPending)
 76ExpandedSubBlockStart.gifContractedSubBlock.gif                dot.gif{
 77InBlock.gif                    // Need to set Cancel if you need to
 78InBlock.gif                    // distinguish how a worker thread completed
 79InBlock.gif                    // i.e., by checking
 80InBlock.gif                    // RunWorkerCompletedEventArgs.Cancelled
 81InBlock.gif                    eventArgs.Cancel = true;
 82InBlock.gif                    break;
 83ExpandedSubBlockEnd.gif                }

 84ExpandedSubBlockEnd.gif            }

 85ExpandedSubBlockEnd.gif        }

 86InBlock.gif        eventArgs.Result = pi.ToString();
 87ExpandedSubBlockEnd.gif    }

 88InBlock.gif
 89InBlock.gif    private static void UpdateDisplayWithMoreDigits(object sender, ProgressChangedEventArgs eventArgs)
 90ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
 91InBlock.gif        string digits = (string)eventArgs.UserState;
 92InBlock.gif
 93InBlock.gif        Console.Write(digits);
 94InBlock.gif
 95ExpandedSubBlockEnd.gif    }

 96InBlock.gif
 97InBlock.gif    static void Complete(object sender, RunWorkerCompletedEventArgs eventArgs)
 98ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
 99InBlock.gif        Console.WriteLine();
100InBlock.gif        if (eventArgs.Cancelled)
101ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
102InBlock.gif            Console.WriteLine("Cancelled");
103ExpandedSubBlockEnd.gif        }

104InBlock.gif        else if (eventArgs.Error != null)
105ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
106InBlock.gif            // IMPORTANT: check error to retrieve any exceptions.     
107InBlock.gif            Console.WriteLine(
108InBlock.gif                "ERROR: {0}", eventArgs.Error.Message);
109ExpandedSubBlockEnd.gif        }

110InBlock.gif        else
111ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
112InBlock.gif            Console.WriteLine("Finished");
113ExpandedSubBlockEnd.gif        }

114InBlock.gif        resetEvent.Set();
115InBlock.gif
116ExpandedSubBlockEnd.gif    }

117ExpandedBlockEnd.gif}

118None.gif
119None.gifpublic class PiDigitCalculator
120ExpandedBlockStart.gifContractedBlock.gifdot.gif{
121InBlock.gif    // dot.gif
122InBlock.gif    public static int StartingAt(int i)
123ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
124InBlock.gif        Thread.Sleep(1000);
125InBlock.gif        return i;
126ExpandedSubBlockEnd.gif    }

127ExpandedBlockEnd.gif}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值