委托调用线程

//创建一个委托线程
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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值