#region
/**
* 用委托(Delegate)的BeginInvoke和EndInvoke方法操作线程
BeginInvoke方法可以使用线程异步地执行委托所指向的方法。然后通过EndInvoke方法获得方法的返回值
(EndInvoke方法的返回值就是被调用方法的返回值),或是确定方法已经被成功调用。
*
*/
private delegate int NewTaskDelegate1(int ms);
private static int newTask1(int ms)
{
Console.WriteLine("任务开始");
System.Threading.Thread.Sleep(ms);
Random random = new Random();
int n = random.Next(10000);
Console.WriteLine("任务完成");
return n;
}
static void Main1(string[] args)
{
NewTaskDelegate1 task = newTask1;
IAsyncResult asyncResult = task.BeginInvoke(2000, null, null);
//EndInvoke方法将被阻塞2秒
int result = task.EndInvoke(asyncResult);
Console.WriteLine(result);
Console.Read();
}
IAsyncResult异步编程
最新推荐文章于 2023-12-23 21:12:06 发布