问题代码在下面,其中包括两个问题。
第一个问题:我用HttpWebRequest来做针对同一地址开启5个线程来同时请求数据,为什么只有两个线程在工作?
第二个问题:如果我去掉了using(FileStream fs= ...)这个包含块所有的线程就都不工作了这是什么原因?
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.Threading;
namespace ConsoleApplication9
{
class Program
{
static void Main(string[] args)
{
Thread[] ts = new Thread[5];
for (int i = 0; i < ts.Length; i++)
{
ts[i] = new Thread(new ThreadStart(down));
ts[i].Name = "线程 " + i.ToString();
ts[i].Start();
}
}
//第一个问题用到的代码
static int ran = 0;
static void down()
{
using (FileStream fs = new FileStream(Thread.CurrentThread.Name, FileMode.Create))
{
string url = "http://im.baidu.com/download/down.php?a=more";
HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;
//req.AddRange(ran, ran + 1024 * 1024 * 10);
Stream stream = req.GetResponse().GetResponseStream();
byte[] buffer = new byte[256];
int i = stream.Read(buffer, 0, 256);
while (i > 0)
{
i = stream.Read(buffer, 0, 256);
Console.WriteLine(Thread.CurrentThread.Name);
fs.Write(buffer, 0, i);
Thread.Sleep(500);
}
}
}
////第二个问题用到的代码
//static int ran = 0;
//static void down()
//{
// string url = "http://im.baidu.com/download/down.php?a=more"";
// HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;
// req.AddRange(1, 500000);
// Stream stream = req.GetResponse().GetResponseStream();
// byte[] buffer = new byte[256];
// int i = stream.Read(buffer, 0, 256);
// while (i > 0)
// {
// i = stream.Read(buffer, 0, 256);
// }
//}
}
}
限制是只用两个的,到ie7都是两个,这个是默认限制:
修改方法:
http://www.cnblogs.com/lishenglyx/archive/2010/01/07/1641190.html
呵呵