1. 程式人生 > >Unity之C#——非同步委託開啟執行緒,三種方法檢測結束

Unity之C#——非同步委託開啟執行緒,三種方法檢測結束

Unity之C#——非同步委託開啟執行緒,三種方法檢測結束 原始碼如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace _004_非同步委託開啟執行緒
{
    class Program
    {
        static int Test(int i, string str)
        {
            Console.WriteLine("我:lisan" + i + str);
            Thread.Sleep(5000);//讓當前執行緒休眠,單位毫秒 ms  模擬查詢的等待過程
            return 19960908;
        }

        static void Main(string[] args)
        {
            ////1.利用迴圈檢測執行緒結束
            //Func<int, string, int> a = Test;
            ////開啟一個新執行緒去執行 a委託的方法
            //IAsyncResult ar = a.BeginInvoke(199610, "的生日是多少?",null, null);
            ////IAsyncResult 獲取執行緒的當前狀態
            //Console.WriteLine("叮噹:主人,請提問!");

            //while (!ar.IsCompleted)
            //{
            //    Thread.Sleep(10);//控制檢測執行緒是否結束的頻率,每10毫秒檢測一次。
            //    Console.WriteLine("查詢中。。。。。");
            //}
            //int res = a.EndInvoke(ar);
            //Console.WriteLine("lisan199610的生日是:" + res);
            //Console.ReadKey();


            ////2.利用回撥函式檢測執行緒結束
            //Func<int, string, int> a = Test;
            ////開啟一個新執行緒去執行 a委託的方法
            //IAsyncResult ar = a.BeginInvoke(199610, "的生日是多少?", OnCallBack, a);
            ////IAsyncResult 獲取執行緒的當前狀態
            //Console.WriteLine("叮噹:主人,請提問!");
            //Console.ReadKey();

            //3.利用回撥函式檢測執行緒結束,並且回撥函式用lambe表示式
            Func<int, string, int> a = Test;
            //開啟一個新執行緒去執行a委託的方法
            a.BeginInvoke(199610, "的生日是多少?",
                ar =>
                {
                    int res = a.EndInvoke(ar);
                    Console.WriteLine("叮噹:lisan199610的生日是:" + res);
                },null);

            Console.WriteLine("叮噹:主人,請提問!");
            Console.ReadKey();

        }

        ////2.回撥函式
        //static void OnCallBack(IAsyncResult ar)
        //{
        //    Func<int, string, int> a = ar.AsyncState as Func<int, string, int>;
        //    int res = a.EndInvoke(ar);
        //    Console.WriteLine("叮噹:lisan199610的生日是:" + res);
        //}
    }
}