BeginInvoke
using System;
using System.Threading;
namespace ConsoleApplication1
{
class BeginInvoke
{
private delegate int NewTaskDelegate(int ms);
static void Main44()
{
NewTaskDelegate task = new NewTaskDelegate(newTask);//委托实例
IAsyncResult asyncResult = task.BeginInvoke(2000, new AsyncCallback(CallBackMethod11), task);//异步程序开始执行 ,当使用BeginInvoke异步调用方法时,如果方法未执行完,EndInvoke方法就会一直阻塞,直到被调用的方法执行完毕
//Thread.Sleep(100);
while (!asyncResult.IsCompleted)
{
Console.Write("*");
Thread.Sleep(100);
}
//END
//使用WaitOne方法等待异步方法执行完成
//while (!asyncResult.AsyncWaitHandle.WaitOne(100, false))//如果指定时间为0,表示不等待,如果为-1,表示永远等待,直到异步调用完成。
//{
// Console.Write("/");
//}
//END
// EndInvoke方法将被阻塞2秒 ,由于异步调用已经完成,因此, EndInvoke会立刻返回结果
//int result = task.EndInvoke(asyncResult);//EndInvoke方法的返回值就是被调用方法的返回值
Console.WriteLine("\nhhh7777");
}
private static int newTask(int ms)
{
//Console.WriteLine("任务开始");
//Thread.Sleep(ms);
Random random = new Random();
int n = random.Next(10000);
//Console.WriteLine("任务完成");
return n;
}
private static void CallBackMethod11(IAsyncResult ar)
{
//从异步状态ar.AsyncState中,获取委托对象
NewTaskDelegate dn = (NewTaskDelegate)ar.AsyncState;
//Thread.Sleep(4666);
//一定要EndInvoke,否则一直阻塞
int r = dn.EndInvoke(ar);
Console.Write(r);
}
}
}
posted on 2011-11-15 22:29 breakpoint 阅读(409) 评论(0) 编辑 收藏 举报