代码之家  ›  专栏  ›  技术社区  ›  Om Deshmane

如何将完成端口操作(I/O绑定函数)排队到CLR线程池

  •  3
  • Om Deshmane  · 技术社区  · 15 年前

    我有一个执行长时间I/O的外部库。我希望创建一个多线程应用程序,它将使用线程池来限制同时执行的线程数 和 我希望将处理这些外部调用的线程添加为完成端口线程(I/O线程),而不是工作线程(以便计算绑定线程的限制)是完整的。

    我有一个代码示例,它省略了外部库,但显示了我已经尝试过的内容。

    有人知道怎么做吗?或者是可能的。谢谢你

    using System;
    using System.Threading;
    using System.Net;
    using System.Net.Sockets;
    using System.Text;
    
    namespace ThreadPoolTest
    {
        class MainApp
        {
            static void Main()
            {
                ThreadPool.SetMaxThreads(10, 10);
                ThreadPool.QueueUserWorkItem(DoWork); //doesn't work - a compute-bound thread 
    
                ThreadPool.SetMaxThreads(10, 10);
    
                 //doesn't work - still a compute-bound thread 
                ((Action<object>)DoWork).BeginInvoke(null, Callback, null);
    
                Console.Read();
            }
    
            static void DoWork(object o)
            {
                ShowAvailableThreads();
                //call to external library - that does a long I/O operation
                Thread.Sleep(10);
            }
    
            static void Callback(IAsyncResult ar)
            {
                ShowAvailableThreads();
            }
    
            static void ShowAvailableThreads()
            {
                int workerThreads, completionPortThreads;
    
                ThreadPool.GetAvailableThreads(out workerThreads,
                   out completionPortThreads);
                Console.WriteLine("WorkerThreads: {0}," +
                   " CompletionPortThreads: {1}",
                   workerThreads, completionPortThreads);
            }
        }
    }
    
    1 回复  |  直到 15 年前
        1
  •  4
  •   Steve Townsend    15 年前

    您可以按说明对I/O线程的工作进行排队 here .

    托管QueueUserWorkItem队列 只处理“工作线程”。 非安全队列重叠队列 I/O线程,以及 在内核上执行异步I/O 已绑定到 通过BindHandle的线程池。