[英]Can I define frequency check for ThreadPool.QueueUserWorkItem?
I implemented a System.Web.IHttpAsyncHandler
to limit website bandwidth usage for files download. 我实现了
System.Web.IHttpAsyncHandler
来限制网站带宽用于文件下载。 Once defined user bandwidth, I need to send a byte[]
every second (or 1000 milliseconds, to be precise). 定义用户带宽后,我需要每秒发送一个
byte[]
(准确地说是1000毫秒)。 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. 一旦进入
ThreadPool.QueueUserWorkItem
,我就无法控制执行代码的频率,因此无需花一秒钟的时间来执行,而这种差异反映了下载吞吐量。
So, my questions are: 因此,我的问题是:
ThreadPool.QueueUserWorkItem
check interval? ThreadPool.QueueUserWorkItem
检查间隔吗? TIA TIA
You shouldn't hang on to a PoolThread like that. 您不应该像那样死守一个PoolThread。 And in general, any Threading solution that uses Sleep() is suspect.
通常,任何使用Sleep()的线程解决方案都是可疑的。
You can use System.Threading.Timer
, I'm not sure about the accuracy (roughly ~20ms) but it will not 'wander off'. 您可以使用
System.Threading.Timer
,我不确定准确性(大约〜20ms),但是它不会“漂移”。
The Timer will replace the while loop inside your delegate. 计时器将替换委托中的while循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.