如何将完成端口操作(I/O 绑定函数)排队到 CLR 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);
}
}
}
I have an external library that does long running I/O. I wish to create a multithreaded application that will use ThreadPool to limit simultaneous number of threads and I wish to add threads handing these external calls as completion port thread (I/O threads) rather than worker threads (so that limit for compute bound threads) is intact.
I have a code sample, that omits external library but shows what I've tried already.
Does anyone know how to do that? Or is it even possible. Thank you
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);
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以按所述对 I/O 线程的工作进行排队 此处。
You can queue work for the I/O threads as described here.