using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ConsoleApplication1
{
class Program
{
private static int Task(int ms)
{
Console.WriteLine("任务开始");
Thread.Sleep(ms);
Random random = new Random();
int n = random.Next(10000);
Console.WriteLine("任务完成");
return n;
}
private delegate int NewTaskDelegate(int ms);
static void Main(string[] args)
{
NewTaskDelegate task = Task;
IAsyncResult asyncResult = task.BeginInvoke(2000, null, null); //第一个参数传递给调用方法
//EndInvoke方法将被阻隔2秒
/*while (!asyncResult.AsyncWaitHandle.WaitOne(100, false))
{
Console.Write("*");
}*/
//EndInvoke方法将被阻隔2秒
while (!asyncResult.IsCompleted)
{
Console.Write("*");
Thread.Sleep(100);
}
int result = task.EndInvoke(asyncResult);
Console.WriteLine(result);
}
}
}
C#异步编程
本文转载:CSDN博客