//创建一个委托线程
static Action test1 = delegate () {
Console.WriteLine("委托调用线程");
};
static void Main(string[] args)
{
test1.BeginInvoke(null, null);//异步调用相当于多线程
Console.ReadKey();
}
//创建一个有参数的委托线程
static Action<int> test2 = (i) =>
{
Console.WriteLine("hello"+i);
};
static void Main(string[] args)
{
test2.BeginInvoke(120,null, null);
}
//有参有委托
static Action<int> test2 = (i) =>
{
Console.WriteLine("hello"+i);
};
//回调函数
static void re(IAsyncResult ir)
{
Console.WriteLine("回调");
int rec = (int)ir.AsyncState;
Console.WriteLine(rec);//输出20
}
static void Main(string[] args)
{
//1.线程传入参数120
//2.线程执行完成后,紧接着执行回调re,并给回调传输参数20
test2.BeginInvoke(120,re, 20);
}
//定义Func有参委托,作为线程执行函数,Func可有返回值
static Func<string, int> test3 = (i) =>
{
Console.WriteLine("hello,"+i);//输出hello,world
return 2120;
};
//线程执行完后的回调函数
static void re(IAsyncResult ir)
{
Console.WriteLine("线程回调");
int rec = (int)ir.AsyncState;
Console.WriteLine(rec);
}
static void Main(string[] args)
{
IAsyncResult ir = test3.BeginInvoke("world", re, 120);//启动线程
while (!ir.IsCompleted)
{//等待线线程结果,不是好的方式
Console.WriteLine("*");
}
//ir.AsyncWaitHandle.WaitOne (2000);//可用此句阻塞,等待结果
int res = test3.EndInvoke(ir);//获取线程返回结果
Console.WriteLine(res);//输出2120
}
//执行结果为:
hello,world
2120
线程回调
120