乐趣区

关于c#:使用线程池

应用线程池(60/217)

3.1、简介

3.2、在线程池中调用委托

  • 内容没看
using System;
using System.Threading;

namespace LionelPro
{
    class Program
    {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();

            string result = poolDelegate.EndInvoke(out threadId, r);
            Console.WriteLine("Thread pool worker thread id:{0}", threadId);
            Console.WriteLine(result);

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

        private delegate string RunOnThreadPool(out int threadId);

        private static void Callback(IAsyncResult ar)
        {Console.WriteLine("Starting a callback...");
            Console.WriteLine("State 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);
        }

        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);
        }
    }
}

3.3、向线程池中放入异步操作

3.4、线程池与并行度

3.5、实现一个勾销选项

3.6、在线程池中应用期待事件处理

3.7、应用计时器

3.8、应用 BackgroundWorker 组件

退出移动版