线程池 BeginInvoke




using System;

usingSystem.Collections.Generic;

using System.Linq;

using System.Text;

usingSystem.Threading;

usingSystem.Threading.Tasks;

 

namespaceConsoleApp1

{

    class Program

    {

        private delegate stringRunnOnThreadPool(out int threadId);

        private static voidCallBack(IAsyncResult ar)

        {

           System.Console.WriteLine("Stard a call back...");

           System.Console.WriteLine("State passed to a callback:{0}",ar.AsyncState);

            System.Console.WriteLine("Is athread pool thread:{0}", Thread.CurrentThread.IsThreadPoolThread);

            System.Console.WriteLine("Thepool worker thread id:{0}", Thread.CurrentThread.ManagedThreadId);

 

        }

        private static string Test(out intthreadId)

        {

           System.Console.WriteLine("Staring...");

            System.Console.WriteLine("Is athread pool thread:{0}", Thread.CurrentThread.IsThreadPoolThread);

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

            threadId =Thread.CurrentThread.ManagedThreadId;

 

            return string.Format("Threadpool worker thread id was:{0}", threadId);

 

        }

        static void Main(string[] args)

        {

            int threadId = 0;

            RunnOnThreadPool poolDelegate =Test;

            var t = new Thread(() =>Test(out threadId));

            t.Start();

            t.Join();

 

            IAsyncResult r =poolDelegate.BeginInvoke(out threadId, CallBack, "a deltegate asynchronouscall");

 

            r.AsyncWaitHandle.WaitOne();

 

            string result =poolDelegate.EndInvoke(out threadId, r);

 

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

 

            System.Console.WriteLine(result);

 

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

            Console.Read();

        }

    }

}

Staring...

Is a thread poolthread:False

Staring...

Is a thread poolthread:True

The pool workerthread id:4

Thread pool workerthread id was:4

Stard a call back...

State passed to acallback:a deltegate asynchronous call

Is a thread poolthread:True

The poolworker thread id:4




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值