2011-02-06 72 views
0

鎖我有這個代碼的註釋區域問題「掛形式」問題與線程和同治鎖

我的程序將掛在那裏!!!!什麼問題?

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); 
     } 
    } 
}

回答

0

調用等待函數返回。 UI線程將運行循環幾分鐘,工作線程將等待UI線程調用並返回。

使用BeginInvoke將任務置於UI線程上而不會阻塞。