problem with lock in thread &managment lock
i have problem in this code in the comment area "hang the form"
my program will hang there!!!! what is problem??
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Threading; namespace WindowsFormsApplication28 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } BackgroundWorker backgw = new BackgroundWorker(); private void button1_Click(object sender, EventArgs e) { backgw.DoWork += new DoWorkEventHandler(k_DoWork); ParameterizedThreadStart start = new ParameterizedThreadStart(startthread); System.Threading.Thread u; int i = 0; while (i < 100) { //u = new System.Threading.Thread(start); //u.Start(i); //1.with thread way backgw.RunWorkerAsync(i); //2.with backgw way Thread.Sleep(1000); lock (y) { Thread.Sleep(1000); } lock(h) i++; } } delegate void j(int h); j b; object h = new object(); object y = new object(); void startthread(object m) { Monitor.Enter(h); Monitor.Enter(y); p1((int)m); Monitor.Exit(h); } void p1(int h) { b = delegate(int q) { label1.Text = string.Format("Step is :{0}", h.ToString()); }; Monitor.Exit(y); label1.Invoke(b); //hang the form???? } void k_DoWork(object sender, DoWorkEventArgs e) { Monitor.Enter(h); Monitor.Enter(y); p1((int)e.Argument); Monitor.Exit(h); } } }
Invoke waits for the function to return. The UI thread will be running the loop for a few minutes, the worker thread will be waiting for the UI thread to invoke and return.
Use BeginInvoke to put the task on the UI thread without blocking.
链接地址: http://www.djcxy.com/p/57928.html下一篇: 锁定线程和管理锁的问题