c#用一个线程同步的简单例子

 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_xmlTransPortTest
14 {
15     public partial class Form1 : Form
16     {
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 关键字可以用来确保代码块完成运行,而不会被其他线程中断。这是通过在代码块运行期间为给定对象获取互斥锁来实现的。

原文地址:https://www.cnblogs.com/jck34/p/2829740.html