WinForm 多线程,高手请进!
我用C#窗体做了一个查询IP地址的程序(从数据库中查询),里面用了线程,但我每次点击搜索时,窗体就不能拖动了,过了一会儿窗体是可以拖动了,但一拖动程序就没有响应了。
为什么???
[解决办法]
[解决办法]
借帖问星星个问题, 现在做一个WCF服务的负载测试工具,简单点说就是创建多个线程(100个以上)访问WCF,但实际使用中发现工具只开了2个端口发送请求,导致线程等待,网上也没找到详细的资料,不知道能否解答
[解决办法]
在Invoke里面写的东西都是委托给主线程来操作的,也就是UI线程来操作,你在Invoke里面用了循环,也就是相当于委托给主线程(也就是UI所在的线程)做循环,当然会不动了。
跟你讲一下子线程和委托应该怎么用:
使用子线程,本来就是为了不影响主线程的操作,所以,不要在子线程中把所有事情都委托给主线程来做,你看看你的方法,子线程里面,上来就开始用this.Invoke,而且子线程的操作都在委托里面,也就是相当于子线程的所有操作都委托给主线程来操作了,这样根本没有起到子线程的作用,而你需要做的是,只有界面的操作才用委托,其他的,都不要放在委托里面。
把程序给你改一下,我就不调试了,你自己试一下:注意看委托使用的位置,只有在
- C# code
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Data.OleDb; using System.Threading; namespace SearchIp { public partial class Form1 : Form { private string ipStr; public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { label4.Text = ""; ipStr = textBox1.Text; Thread t = new Thread(new ThreadStart(SearchThread)); t.Start(); } private void Form1_Load(object sender, EventArgs e) { progressBar1.Maximum = 364875; } public void SearchThread() { string[] ipfd = ipStr.Split('.'); int ip1 = Convert.ToInt32(ipfd[0]); int ip2 = Convert.ToInt32(ipfd[1]); int ip3 = Convert.ToInt32(ipfd[2]); int ip4 = Convert.ToInt32(ipfd[3]); string sqlcmd="select * from IP_Address where IPStart like '%"+(ip1+"."+ip2)+"%'"; if(ip1 <12) sqlcmd="select * from IP_Address where IPStart like '%"+ip1+"%'"; OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=IP.mdb"); con.Open(); OleDbCommand cmd = new OleDbCommand(sqlcmd, con); OleDbDataReader dr = cmd.ExecuteReader(); while (dr.Read()) { int ts = Convert.ToInt32(dr["Code"]); this.Invoke((MethodInvoker)delegate { progressBar1.Value = ts; progressBar1.Refresh(); label4.Text = ts + ""; label4.Refresh(); }); string[] IPS = dr["IPStart"].ToString().Split('.'); string[] IPE = dr["IPEnd"].ToString().Split('.'); int ips1 = Convert.ToInt32(IPS[0]); int ips2 = Convert.ToInt32(IPS[1]); int ips3 = Convert.ToInt32(IPS[2]); int ips4 = Convert.ToInt32(IPS[3]); int ipe1 = Convert.ToInt32(IPE[0]); int ipe2 = Convert.ToInt32(IPE[1]); int ipe3 = Convert.ToInt32(IPE[2]); int ipe4 = Convert.ToInt32(IPE[3]); if (ip1 >= ips1 && ip2 >= ips2 && ip3 >= ips3 && ip4 >= ips4 && ip1 <= ipe1 && ip2 <= ipe2 && ip3 <= ipe3 && ip4 <= ipe4) { this.Invoke((MethodInvoker)delegate { label2.Text = label2.Text + dr["IP_Address"].ToString(); }); break; } Thread.Sleep(2); } con.Close(); cmd.Dispose(); dr.Dispose(); } } }