1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.Linq; 7 using System.Text; 8 using System.Threading; 9 using System.Threading.Tasks;10 using System.Windows.Forms;11 using System.Xml;12 13 namespace csharp_xmlTransPortTest14 {15 public partial class Form1 : Form16 {17 public delegate void ThreadProcess();18 public Form1()19 {20 InitializeComponent();21 22 23 }24 25 XmlDocument statusDoc = new XmlDocument();26 public void xx()27 {28 thread0 = new Thread(new ThreadStart(startedcross));29 thread0.Start();30 thread1 = new Thread(new ThreadStart(started1cross1));31 thread1.Start();32 }33 34 private int i = 100;35 private Thread thread0;36 private Thread thread1;37 private object str = new object();38 private void startedcross()39 {40 ThreadProcess tp = new ThreadProcess(started);41 tp.BeginInvoke(null, null);42 }43 44 private void started1cross1()45 {46 ThreadProcess tp1 = new ThreadProcess(started1);47 tp1.BeginInvoke(null, null);48 }49 private void started()50 {51 while (true)52 {53 //string str = "32";54 lock (str)55 {56 if (i > 0)57 {58 textBox1.Text += ((i--).ToString() + "\r\n");59 }60 }61 }62 }63 64 private void started1()65 {66 while (true)67 {68 lock (str)69 {70 if (i > 0)71 {72 textBox1.Text += ((i--).ToString() + "\r\n");73 }74 }75 }76 }77 78 private void button1_Click(object sender, EventArgs e)79 {80 xx();81 }82 83 }84 }
lock 關鍵字可以用來確保代碼塊完成運行,而不會被其他線程中斷。這是通過在代碼塊運行期間為給定對象擷取互斥鎖來實現的。