1. 程式人生 > 其它 >序列化與檔案的輸入輸出

序列化與檔案的輸入輸出

        private void button1_Click(object sender, EventArgs e)
        {
            Console.WriteLine($"主執行緒:{Thread.CurrentThread.ManagedThreadId}");
            InitBackgroundTask();
        }

        private void InitBackgroundTask()
        {
            BackgroundWorker worker = new BackgroundWorker();
            worker.DoWork 
+= new DoWorkEventHandler ( (object sender, DoWorkEventArgs e) => { Console.WriteLine($"--------------- start busy task, 執行緒: {Thread.CurrentThread.ManagedThreadId}"); for (int i = 0; i < 100; i++) { worker.ReportProgress(i
+ 1); e.Result = 100 + i; Thread.Sleep(30); } Console.WriteLine("--------------- busy task finished."); } ); worker.ProgressChanged += new ProgressChangedEventHandler ( (
object sender, ProgressChangedEventArgs e) => { Console.WriteLine($"Task progress: {e.ProgressPercentage}"); } ); worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler ( (object sender, RunWorkerCompletedEventArgs e) => { Console.WriteLine($"任務完成,可以在這裡分配其他任務,執行緒: {Thread.CurrentThread.ManagedThreadId}"); } ); worker.WorkerReportsProgress = true; worker.RunWorkerAsync(100); }

輸出結果:

主執行緒:1
--------------- start busy task, 執行緒: 3
Task progress: 1
Task progress: 2
Task progress: 3
...
...
Task progress: 97 Task progress: 98 Task progress: 99 Task progress: 100 --------------- busy task finished. 任務完成,可以在這裡分配其他任務,執行緒: 1