C# 异步
class Invoke
{
#region 异步不带返回值
//声明委托
public delegate void AsyncEventHandler();
//异步方法
void Event1()
{
Console.WriteLine("Event1 Start!");
System.Threading.Thread.Sleep(4000);
Console.WriteLine("Event1 End!");
}
//同步方法
void Event2()
{
Console.WriteLine("Event2 Start!");
int i = 0;
while (i < 20)
{
i = i + 1;
Console.WriteLine("Event2...."+i.ToString());
}
Console.WriteLine("Event2 End!");
}
public void Show()
{
long start = 0;
long end = 0;
Console.WriteLine("Ready");
start = DateTime.Now.Ticks;
//实例化委托
AsyncEventHandler asy = new AsyncEventHandler(Event1);
//异步调用开始,没有回调函数和AsyState,都为null
IAsyncResult ia=asy.BeginInvoke(null,null);
//同步方法开始
Event2();
//异步结束,若没有结束,一直阻塞到调用完成,在此返回值函数的return,若有返回值,
asy.EndInvoke(ia);
end = DateTime.Now.Ticks;
Console.WriteLine("时间刻度差:"+Convert.ToString(end-start));
Console.ReadLine();
}
#endregion
#region 异步带返回值
private string MethodName(int num, out int retNum)
{
retNum = num;
return "Hell";
}
private delegate string invokeDelegate(int num, out int retNum);
public void Run()
{
invokeDelegate del = new invokeDelegate(MethodName);
int i;
IAsyncResult iar = del.BeginInvoke(525,out i,null,null);
//去做别的事情
string result = del.EndInvoke(out i,iar);
Console.WriteLine(i.ToString() + "____" + result);
}
#endregion
}