多线程下载的时候为什么有线程偷懒,只有两个线程在工作,如图我开启了5个线程,却只有0和3在工作。
1 using System;
2 using System.Collections.Generic;
3 using System.Text;
4 using System.Drawing;
5 using System.Net;
6 using System.IO;
7 using System.Threading;
8
9 namespace ConsoleApplication9
10 {
11 class Program
12 {
13 static void Main(string[] args)
14 {
15
16
17 Thread[] ts = new Thread[5];
18 for (int i = 0; i < ts.Length; i++)
19 {
20 ts[i] = new Thread(new ThreadStart(down));
21 ts[i].Name = "线程 " + i.ToString();
22 ts[i].Start();
23
24 }
25 }
26
27 static int ran = 0;
28 static void down()
29 {
30 using (FileStream fs = new FileStream(Thread.CurrentThread.Name, FileMode.Create))
31 {
32 string url = "http://dl_dir.qq.com/qqfile/qq/QQ2010/QQ2010Beta2.exe";
33 HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;
34 req.AddRange(ran, ran + 1024 * 1024 * 10);
35 Stream stream = req.GetResponse().GetResponseStream();
36 byte[] buffer = new byte[256];
37 int i = stream.Read(buffer, 0, 256);
38 while (i > 0)
39 {
40 i = stream.Read(buffer, 0, 256);
41 Console.WriteLine(Thread.CurrentThread.Name);
42 fs.Write(buffer, 0, i);
43 Thread.Sleep(500);
44 }
45 }
46
47 }
48
49
50 }
51 }
问题2,如果我把下载方法改成下面这样,线程都不工作了,似乎是死锁?
这段代码的第7行是添加下载范围,如果没这段似乎就不出现此问题了,难道是ms的基础类锁定有问题吗
1
2 static int ran = 0;
3 static void down()
4 {
5 string url = "http://dl_dir.qq.com/qqfile/qq/QQ2010/QQ2010Beta2.exe";
6 HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;
7 req.AddRange(1,500000);
8 Stream stream = req.GetResponse().GetResponseStream();
9 byte[] buffer = new byte[256];
10 int i = stream.Read(buffer, 0, 256);
11 while (i > 0)
12 {
13 i = stream.Read(buffer, 0, 256);
14 }
15 }
错误如图(把项目暂停时查看变量值才知道线程都已经停了,可它们还没工作呢)
请高手帮忙解决下啊
webrequest好像有并发线程数量的限制问题,是可以修改的,你试着改一下看看:)