using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Runtime.Remoting.Messaging;
namespace 異步委托
{
/// <summary>
/// 說明異步委托調用時會產生一個新的線程,不會阻塞主線程,
/// 前提是使用回調函數,而不是直接使用委托的.endinvoke方法獲取結果
/// </summary>
class Program
{
public delegate int AddDel(int x, int y);
static void Main(string[] args)
{
//定義委托
AddDel addDel = new AddDel(AddFunc);
Console.WriteLine("主線程開始執行...{0}",Thread.CurrentThread.ManagedThreadId);
//開始異步調用委托
addDel.BeginInvoke(2, 3, Callback, 2); //第三個參數回調函數,第四個參數,額外參數
Console.WriteLine("主線程執行完畢!");
Console.ReadKey();
}
static int AddFunc(int x, int y)
{
Console.WriteLine("子線程在執行:{0}",Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(3000);
return x + y;
}
static void Callback(IAsyncResult ar)
{
AsyncResult asy = (AsyncResult)ar;
//獲取代理信息
AddDel addDel = (AddDel)asy.AsyncDelegate;
//獲取返回結果
int result = addDel.EndInvoke(ar);
//獲取額外參數
int otherData = (int)asy.AsyncState;
Console.WriteLine("子線程執行完畢!{0},執行結果:{1},額外參數:{2}",Thread.CurrentThread.ManagedThreadId
,result,otherData);
}
}
}