C# 调用委托线程BeginInvoke与EndInvoke

2 篇文章 0 订阅


第一步,委托的申明

private delegate string RunOnThreadPool(out int threadId);

第二步,将被作为线程运行的函数

private static string Test(out int threadId)
{
    Console.WriteLine("starting...");
    Console.WriteLine("is thread pool thread: {0}", Thread.CurrentThread.IsThreadPoolThread);
    Thread.Sleep(TimeSpan.FromSeconds(2));
    threadId = Thread.CurrentThread.ManagedThreadId;
    return string.Format("thread pool worker thread id was:{0}", threadId);
}

第三步,回调函数

private static void Callback(IAsyncResult ar)
{
    Console.WriteLine("starting a callback...");
    Thread.Sleep(TimeSpan.FromSeconds(2));
    Console.WriteLine("starting passed to a callback:{0}", ar.AsyncState);
    Console.WriteLine("is thread pool thread: {0}", Thread.CurrentThread.IsThreadPoolThread);
    Console.WriteLine("thread pool worker thread id: {0}", Thread.CurrentThread.ManagedThreadId);
}

第四步,主函数

static void Main(string[] args)
{
    int threadId = 0;
    // 申明对函数的引用
    RunOnThreadPool poolDelegate = Test;
    var t = new Thread(() => Test(out threadId));
    t.Start();
    t.Join();
    Console.WriteLine("thread id: {0}", threadId);
    //回调函数在委托函数调用结束后开始
    IAsyncResult r = poolDelegate.BeginInvoke(out threadId, Callback, "a delegate asynchronous call");
    //等待,直到线程结束
    r.AsyncWaitHandle.WaitOne();
    //while(!r.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(0.1)))
    //{
    //    Console.Write("*");
    //}
    //获取线程运行结束后的结果
    string result = poolDelegate.EndInvoke(out threadId, r);

    Console.WriteLine("thread pool worker thread id: {0}", threadId);

    Console.WriteLine(result);

    Thread.Sleep(TimeSpan.FromSeconds(2));

    Console.ReadKey();
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值