异步调用委托的3种方法
输出: 100
400
900
using System;
using System.Collections.Generic;
using System.Text;
namespace AsyncDelegate
{
class Program
{
delegate int IntIntDelegate(int x);//生明一个委托
int Square(int x)
{
return x * x;
}
void AsyncDelegateExample()
{
IntIntDelegate f = Square;
//方法一
IAsyncResult ar1=f.BeginInvoke(10,null,null);
while (!ar1.IsCompleted)//循环直到异步完成
Console.WriteLine(f.EndInvoke(ar1));
//do some work
//方法二
IAsyncResult ar2= f.BeginInvoke(20, null, null);
//do some work
ar2.AsyncWaitHandle.WaitOne();//等待直到异步完成
Console.WriteLine(f.EndInvoke(ar2));
//方法三 完成后调用回调函数,取得结束通知的结果
IAsyncResult ar3 = f.BeginInvoke(30, AsyncDelegateCallback, f);
}
void AsyncDelegateCallback(IAsyncResult ar)//回调函数
{
IntIntDelegate f = (IntIntDelegate)ar.AsyncState;
if (ar.IsCompleted)
{
Console.WriteLine(f.EndInvoke(ar));
}
//Console.WriteLine(f.EndInvoke(ar));
}
static void Main(string[] args)
{
Program test = new Program();
test.AsyncDelegateExample();//客户端调用
}
}
}
using System.Collections.Generic;
using System.Text;
namespace AsyncDelegate
{
class Program
{
delegate int IntIntDelegate(int x);//生明一个委托
int Square(int x)
{
return x * x;
}
void AsyncDelegateExample()
{
IntIntDelegate f = Square;
//方法一
IAsyncResult ar1=f.BeginInvoke(10,null,null);
while (!ar1.IsCompleted)//循环直到异步完成
Console.WriteLine(f.EndInvoke(ar1));
//do some work
//方法二
IAsyncResult ar2= f.BeginInvoke(20, null, null);
//do some work
ar2.AsyncWaitHandle.WaitOne();//等待直到异步完成
Console.WriteLine(f.EndInvoke(ar2));
//方法三 完成后调用回调函数,取得结束通知的结果
IAsyncResult ar3 = f.BeginInvoke(30, AsyncDelegateCallback, f);
}
void AsyncDelegateCallback(IAsyncResult ar)//回调函数
{
IntIntDelegate f = (IntIntDelegate)ar.AsyncState;
if (ar.IsCompleted)
{
Console.WriteLine(f.EndInvoke(ar));
}
//Console.WriteLine(f.EndInvoke(ar));
}
static void Main(string[] args)
{
Program test = new Program();
test.AsyncDelegateExample();//客户端调用
}
}
}
输出: 100
400
900