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

Om *_*ane 4 .net c# io multithreading threadpool

我有一个执行长时间运行 I/O 的外部库。我希望创建一个多线程应用程序,该应用程序将使用 ThreadPool 来限制并发线程数,并且我希望添加处理这些外部调用的线程作为完成端口线程(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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Ste*_*end 5

您可以按此处所述对 I/O 线程的工作进行排队。

托管的 QueueUserWorkItem 仅将工作排队到“工作线程”。UnsafeQueueNativeOverlapped 排队到 I/O 线程,就像在通过 BindHandle 绑定到 ThreadPool 的内核对象上执行的异步 I/O 的完成一样。