線程----WaitHandle抽象基類(等待句柄)

例子:c#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace ConsoleApplication6
{
    class Program
    {
        private delegate int AsycTaskDelegate(int i, int j);
        static void Main(string[] args)
        {
            AsycTaskDelegate std = AsycTask;
            IAsyncResult sr = std.BeginInvoke(1, 1000, null, null);
            //設置等待時間2秒鐘,若是在3秒鐘內完成任務,則執行下面的方法
            if (sr.AsyncWaitHandle.WaitOne(2000))
            {
                Console.WriteLine("收到信號");
            }
            else
            {
                Console.WriteLine("信號丟失");
            }
            Console.WriteLine(std.EndInvoke(sr));
            Console.ReadKey();
        }
        private static int AsycTask(int i, int j)
        {
            Console.WriteLine("請等待...");
            Thread.Sleep(j);
            return ++i;
        }
    }
}

wKioL1TaKd6SP_n5AAAlbZAH6ag594.jpg