c#用一個線程同步的簡單例子

來源:互聯網
上載者:User
 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 關鍵字可以用來確保代碼塊完成運行,而不會被其他線程中斷。這是通過在代碼塊運行期間為給定對象擷取互斥鎖來實現的。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.