WaitHandle.WaitOne()

 

WaitHandle.WaitOne() 用來等待任務執行的結果,

或是在一段時間內,去等待任務執行的結果。

WaitHandle.WaitOne() 有五種多載方法。

 

一、public virtual bool WaitOne();

using System;
using System.Threading;
using System.Runtime.Remoting.Messaging;

namespace ConsoleApp1
{
    public class AsyncDemo
    {
        public string TestMethod(string name, int callDuration)
        {
            Console.WriteLine("ManagedThreadId:" + Thread.CurrentThread.ManagedThreadId + " " + name + " 開始");
            Thread.Sleep(callDuration);
            Console.WriteLine("ManagedThreadId:" + Thread.CurrentThread.ManagedThreadId + " " + name + " 結束");
            return name + " complete";
        }
    }

    public delegate string AsyncMethodCaller(string name, int callDuration);

    class Program
    {
        public static void Main()
        {
            AsyncDemo ad = new AsyncDemo();
            AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod);

            IAsyncResult result10 = caller.BeginInvoke("任務10秒", 10000, null, null);
            IAsyncResult result15 = caller.BeginInvoke("任務15秒", 15000, null, null);
            IAsyncResult result20 = caller.BeginInvoke("任務20秒", 20000, null, null);

            // Wait for the WaitHandle to become signaled.
            result20.AsyncWaitHandle.WaitOne();

            // Perform additional processing here.
            // Call EndInvoke to retrieve the results.
            string returnValue = caller.EndInvoke(result20);

            // Close the wait handle.
            result20.AsyncWaitHandle.Close();

            Thread.Sleep(5000);
            Console.WriteLine("ManagedThreadId:" + Thread.CurrentThread.ManagedThreadId + "主執行緒5秒");

            Console.ReadKey();
        }
    }
}

執行畫面為

 

二、public virtual bool WaitOne(TimeSpan timeout);

 

三、public virtual bool WaitOne(TimeSpan timeout, bool exitContext);

 

四、public virtual bool WaitOne(int millisecondsTimeout);

 

五、public virtual bool WaitOne(int millisecondsTimeout, bool exitContext);

 

參考資料:

WaitHandle Class