关于多线程的问题,线程是不是死锁了?
- C# code
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Net;using System.Windows.Forms;using System.Text.RegularExpressions;using System.Threading;namespace WindowsFormsApplication1{ public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { textBox1.Text = "www.baidu.com"; } private void button1_Click(object sender, EventArgs e) { Thread[] thraed = new Thread[5]; ThreadStart start = new ThreadStart(Download); for (int i = 0; i < 5; ++i) { thraed[i] = new Thread(start); thraed[i].Start(); } } public string[] GetSiteInfo(string uri) { string[] info = new string[5]; info[0] = uri; //保存域名 info[1] = GetIP(uri); //保存IP info[2] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); if (!Regex.IsMatch(uri, "http://", RegexOptions.IgnoreCase)) { uri = "http://" + uri; } double timeStart = System.Environment.TickCount; //获取系统开机到现在的时间 HttpWebRequest hw = (HttpWebRequest)WebRequest.Create(uri); try { WebResponse wr = hw.GetResponse(); double timeEnd = System.Environment.TickCount; //获取系统开机到现在的时间 double dTime = (timeEnd - timeStart) / 1000; //计算网站的访问速度 string time = dTime.ToString() + " 秒"; info[3] = time; info[4] = "true"; } catch (Exception e) { info[3] = e.Message; info[4] = "false"; } return info; } public string GetIP(string hostName) { IPHostEntry ipHost = Dns.GetHostEntry(hostName); return ipHost.AddressList[0].ToString(); } private delegate void input(); private void Download() { while (true) { Thread.Sleep(100); textBox2.BeginInvoke(new input(show)); } } private void show() { string[] info = new string[4]; info = GetSiteInfo(textBox1.Text.Trim()); textBox2.AppendText("域名:" + info[0] + "\r\nIP:" + info[1] + "\r\n访问时间:" + info[2] + "\r\n响应速度:" + info[3] + "\r\n\r\n"); } }}
各位走过路过的大大们看看,上面的代码是不是发生死锁了?
我对多线程的知识不是很了解,调试了几个小时了,还是没找到原因
点击button1控件运行时,textBox2控件就显示下载了两次,然后程序就不幸身亡
蛋疼啊,各位大大看看到底哪出问题了,小弟在此谢过
[解决办法]
你还丢了很重要一句
WebResponse wr = hw.GetResponse();
double timeEnd = System.Environment.TickCount; //获取系统开机到现在的时间
double dTime = (timeEnd - timeStart) / 1000; //计算网站的访问速度
string time = dTime.ToString() + " 秒";
info[3] = time;
info[4] = "true";
wr.Close();
[解决办法]
你的多线程异步给处理方法的时候 只要起到传递和分配作用就好
其他的不用管