Bvd*_*Ven 3 c# block threadpool
我有一个 C# 控制台应用程序,其中有一个线程池。在线程池中将有一个执行连续方法的类(直到它运行了一段时间或知道何时停止)。该方法连接到 HttpWebResponse 流并继续阅读它。
问题是在短时间内所有线程都只做自己的事情,但是只有一个线程继续显示它的输出,其余的则在等待该线程。
这是为每个线程执行的方法。
function void ReadStream()
byte[] buf = new byte[8192];
String domain = streamingUrl
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(domain);
HttpWebResponse response = (HttpWebResponse)
request.GetResponse();
Stream resStream = response.GetResponseStream();
string tempString = null;
int count;
do
{
// fill the buffer with data
count = resStream.Read(buf, 0, buf.Length);
if (count != 0)
{
tempString = Encoding.ASCII.GetString(buf, 0, count);
try
{
mySqlManager.SaveResult(tempString);
Console.WriteLine("Been here");
Thread.Sleep(1000);
}
catch (Exception e)
{
}
}
}
while (count > 0);
}
Run Code Online (Sandbox Code Playgroud)
首先,您应该将response和包裹resStream在using块中以确保它们被正确处理。
其次,在我看来,将长时间运行的线程放入ThreadPool并不是最好的主意。ThreadPool该类的想法是它允许您将相对较小的操作排队,而为每个操作生成一个新线程会很浪费。如果您的操作需要花费大量时间来运行,我建议您实际Thread为每个操作创建专用对象。
| 归档时间: |
|
| 查看次数: |
527 次 |
| 最近记录: |