我可以定义 ThreadPool.QueueUserWorkItem 的频率检查吗?
我实现了 System.Web.IHttpAsyncHandler 来限制文件下载的网站带宽使用量。一旦定义了用户带宽,我需要每秒(准确地说是 1000 毫秒)发送一个 byte[]
。类似于:
public class DownloadHandler : IHttpAsyncHandler
{
public IAsyncResult BeginProcessRequest(
HttpContext context, AsyncCallback cb, object extraData)
{
// user can download that file?
DownloadAsync download = new DownloadAsync(...);
download.StartDownload()
return download;
}
}
class DownloadAsync : IAsyncResult
{
// ...
public void StartDownload()
{
ThreadPool.QueueUserWorkItem(new WaitCallback(startAsyncTask));
}
private void startAsyncTask(object state)
{
// ...
while (context.Response.IsClientConnected &&
offset < data.Arquivo.Tamanho)
{
// ... do stuff
context.Response.OutputStream.Write(buffer, 0, readCount);
// ... more stuff
Thread.Sleep(1000 - (int)elapsed.TotalMilliseconds);
}
}
}
一旦进入 ThreadPool.QueueUserWorkItem,我就失去了对代码执行频率的控制,因此不需要一秒钟的时间来执行,并且这种差异反映在下载吞吐量上。
所以,我的问题是:
- 我可以定义 ThreadPool.QueueUserWorkItem 检查间隔吗?
- 如果没有,是否有另一种方法可以实现此要求(带宽限制?)
- 如果没有,我可以有一匹小马吗?
TIA
I implemented a System.Web.IHttpAsyncHandler
to limit website bandwidth usage for files download. Once defined user bandwidth, I need to send a byte[]
every second (or 1000 milliseconds, to be precise). Something like:
public class DownloadHandler : IHttpAsyncHandler
{
public IAsyncResult BeginProcessRequest(
HttpContext context, AsyncCallback cb, object extraData)
{
// user can download that file?
DownloadAsync download = new DownloadAsync(...);
download.StartDownload()
return download;
}
}
class DownloadAsync : IAsyncResult
{
// ...
public void StartDownload()
{
ThreadPool.QueueUserWorkItem(new WaitCallback(startAsyncTask));
}
private void startAsyncTask(object state)
{
// ...
while (context.Response.IsClientConnected &&
offset < data.Arquivo.Tamanho)
{
// ... do stuff
context.Response.OutputStream.Write(buffer, 0, readCount);
// ... more stuff
Thread.Sleep(1000 - (int)elapsed.TotalMilliseconds);
}
}
}
Once in ThreadPool.QueueUserWorkItem
, I lose control over frequency my code is being executed, so it don't take a second to execute, and that difference reflects on download throughput.
So, my questions are:
- Can I define
ThreadPool.QueueUserWorkItem
check interval? - If not, are there another approach to achieve this requirement (bandwidth throttling?)
- If not, can I have a pony?
TIA
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你不应该像那样坚持使用 PoolThread。一般来说,任何使用 Sleep() 的线程解决方案都是值得怀疑的。
您可以使用
系统。 Threading.Timer
,我不确定准确性(大约~20ms),但它不会“偏离”。计时器将取代委托内的 while 循环。
You shouldn't hang on to a PoolThread like that. And in general, any Threading solution that uses Sleep() is suspect.
You can use
System.Threading.Timer
, I'm not sure about the accuracy (roughly ~20ms) but it will not 'wander off'.The Timer will replace the while loop inside your delegate.