異世界


2018年8月4日 星期六

async、 await & Task C#

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using System.Diagnostics;
using System.Threading;

namespace WindowsFormsApplication1
{
     public partial class Form1 : Form
     {
         public Form1()
         {
             InitializeComponent();
         }

        private void button1_Click(object sender, EventArgs e)
         {
             ThreadMathed(++CallTimes);
             ThreadMathed(++CallTimes);
             ThreadMathed(++CallTimes);
             ThreadMathed(++CallTimes);
             ThreadMathed(++CallTimes);
         }

        /* 主線程 */
         int CallTimes = 0;
         private async void ThreadMathed(int calltimes)
         {
             int Times = calltimes;
             lvAnalysisResult.Items.Add( string.Format("[{0}]:Please wait while analysing the population.", Times));

            try
             {
                 /// 程式寫法[1] : 以另外一個 class 來撰寫 子線程
                 /// ---------------------------------------------------------------------------
                 /// await        new        AnalysisEngine(CallTimes).AnalyzePopulationAsync();
                 /// 非同步等待   建新實體   AnalysisEngine  傳入參數   執行實體內的 Action
                 /// ---------------------------------------------------------------------------
                 //
                 //.. string result = await new AnalysisEngine(CallTimes).AnalyzePopulationAsync();

                /// 程式寫法[2] : 以黏巴達寫法,直接產生子線程區塊
                 /// ---------------------------------------------------------------------------
                 /// await        Task      <string>.    Factory.StartNew
                 /// 非同步等待   建新實體<傳回值型態>   並開始執行
                 ///
                 /// () =>                    { ............. }
                 /// 黏巴達寫法省缺Task物件      Action 的區塊
                 /// ---------------------------------------------------------------------------
                 //
                 string result = await Task<string>.Factory.StartNew
                 (
                     () =>
                         {
                             int Index = Times; //.. 記憶被呼叫的次序

                            //..模擬程式耗時的活動
                             int R = new Random().Next(1, 10000);
                             Thread.Sleep(R);
                            
                             return string.Format("[{0}]:Random Sleep ={1} ms", Index, R);
                         }
                 );

                //.. 印出回傳值
                 lvAnalysisResult.Items.Add(result.ToString());
             }
             catch (System.Exception exp)
             {
                 lvAnalysisResult.Items.Add( exp.Message + Thread.CurrentThread.Name);
             }
         }
     }


     /* 子線程 Class */
     class AnalysisEngine
     {
         private int Index { get; set; } //.. 記憶被呼叫的次序
         public AnalysisEngine(int index) { Index = index; }
        
         public Task<string> AnalyzePopulationAsync()
         {
             Task<string> task = new Task<string>(AnalyzePopulation);
             task.Start();

            return task;
         }

        //..模擬程式耗時的活動
         public string AnalyzePopulation()
         {
             //Sleep is used to simulate the time consuming activity.
             int R = new Random().Next(1, 10000);
             Thread.Sleep(R);
             return string.Format("[{0}]:Random Sleep ={1} ms", Index, R);
         }
     }
}

沒有留言:

張貼留言