private static void SummarizeResults(DoBackgroundwork bgw, long mainTotal) { if (bgw.CompleteNormally) { Console.WriteLine("\nBackground completed Normally"); Console.WriteLine("Background total = {0}", bgw.BackgroundTotal); } else { Console.WriteLine("\nBackground Cancelled"); } Console.WriteLine("Main total = {0}", mainTotal); }
static void Main() { GiveInstructionsToTheUser(); OutputTheSummaryHeaders(); //创建并打开Background Worker DoBackgroundwork bgw = new DoBackgroundwork(); bgw.StartWorker(); //在主线程启动计算。对于每一次循环,检查是否用户已经取消了后台线程。 //在计算之后,进行短暂的休眠,这样程序可以慢一点,使得主线程不会比后台更快 long mainTotal = 0; for (int i = 0; i < 5; i++) { if (Program.CheckForCancelInput()) bgw.Cancle(); mainTotal += DoBackgroundwork.CalculateTheSequence(100000000); Thread.Sleep(200); Console.WriteLine(" {0}%",(i+1)*20); } SummarizeResults(bgw, mainTotal); Console.ReadLine(); }