日期:2014-05-18 浏览次数:20771 次
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Data.SqlClient; using System.Threading; using System.Diagnostics; namespace ThreadApp { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private delegate void Delemethod(); DataTable dt = null; private void button1_Click(object sender, EventArgs e) { Thread th=new Thread(new ThreadStart(delegate { SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=JH_Achive;user id=sa;password=UYENSKLAY==;"); SqlCommand commm = conn.CreateCommand(); conn.Open(); commm.CommandText = "select * from t_houseregbase"; SqlDataAdapter sa = new SqlDataAdapter(commm); DataSet sd = new DataSet(); sa.Fill(sd); dt = sd.Tables[0]; dgv.BeginInvoke(new Delemethod(dataBond)); })); th.Start(); FormWait fw=new FormWait (); fw.ShowDialog(); Thread.Sleep(5000); fw.Close(); if (dt!=null&&dt.Rows.Count > 0) { th.Abort(); MessageBox.Show("查询完成!!!!"); } else { MessageBox.Show("查询出错!!!!"); } } public void dataBond() { dgv.DataSource = dt; } private void button2_Click(object sender, EventArgs e) { } } }
private delegate DataTable Delemethod(); private void button1_Click(object sender, EventArgs e) { this.Visible = false; FormWait fw = new FormWait(); fw.Show(); ThreadPool.QueueUserWorkItem(param => { Delemethod dt = () => { SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=JH_Achive;user id=sa;password=UYENSKLAY==;"); SqlCommand commm = conn.CreateCommand(); conn.Open(); commm.CommandText = "select * from t_houseregbase"; SqlDataAdapter sa = new SqlDataAdapter(commm); DataTable dtbl = new DataTable(); sa.Fill(dtbl); return dtbl; }; IAsyncResult iar = dt.BeginInvoke(null, null); bool r = iar.AsyncWaitHandle.WaitOne(5000); this.Invoke((MethodInvoker)(() => { fw.Close(); this.Visible = true; if (r) { dgv.DataSource = dt.EndInvoke(iar); } else { MessageBox.Show("查询出错!!!!"); } })); }); }
------解决方案--------------------
对于button1_Click方法,它只要几毫秒、“一瞬间”就执行完了,这才是多线程编程。因为子线程去执行额外的工作,而窗口线程根本不阻塞,而是干完了button1_Click方法之后立刻去用于处理窗口消息循环中的其它事件去了。
------解决方案--------------------
楼上那些匿名函数调用法,看着真累啊,我还是使用最原始的方法吧 请sp1234老大指教 我怎么觉得我陷入了一种因为事件而使用委托的地步了呢? using System; using System.Collections