代码
1using System; 2using System.Collections.Generic; 3using System.ComponentModel; 4using System.Data; 5using System.Drawing; 6using System.Text; 7using System.Windows.Forms; 8 9using System.Threading;1011namespace CSharpGeriac12{13 public partial class Form1 : Form14 {15 public Form1()16 {17 InitializeComponent();1819 Thread t = new Thread(new ThreadStart(ChangeLabel));20 t.Start();21 }2223 private void ChangeLabel()24 {25 for (int i = 0; i < 100; ++i)26 {27 SetLabelText(i);28 Thread.Sleep(1000);29 }30 }3132 private void SetLabelText(int number)33 {34 // label.Text = number.ToString();35 // Do NOT do this, as we are on a different thread.3637 // Check if we need to call BeginInvoke.38 if (this.InvokeRequired)39 {40 // Pass the same function to BeginInvoke,41 // but the call would come on the correct42 // thread and InvokeRequired will be false.43 this.BeginInvoke(new SetLabelTextDelegate(SetLabelText),44 new object[] { number });4546 return;47 }4849 label1.Text = number.ToString();5051 }5253 private delegate void SetLabelTextDelegate(int number);54 }55}
Another Example:
别一例子
1using System; 2using System.Drawing; 3using System.Threading; 4using System.Windows.Forms; 5 6class Program : Form 7{ 8 private System.Windows.Forms.ProgressBar _ProgressBar; 910 [STAThread]11 static void Main()12 {13 Application.Run(new Program());14 }1516 public Program()17 {18 InitializeComponent();19 ThreadStart threadStart = Increment;20 threadStart.BeginInvoke(null, null);21 }2223 void UpdateProgressBar()24 {25 if (_ProgressBar.InvokeRequired)26 {27 MethodInvoker updateProgressBar = UpdateProgressBar;28 _ProgressBar.Invoke(updateProgressBar);29 }30 else31 {32 _ProgressBar.Increment(1);33 }34 }3536 private void Increment()37 {38 for (int i = 0; i < 100; i++)39 {40 UpdateProgressBar();41 Thread.Sleep(100);42 }43 if (InvokeRequired)44 {45 // Close cannot be called directly from 46 // a non-UI thread. 47 Invoke(new MethodInvoker(Close));48 }49 else50 {51 Close();52 }53 }5455 private void InitializeComponent()56 {57 _ProgressBar = new ProgressBar();58 SuspendLayout();5960 _ProgressBar.Location = new Point(13, 17);61 _ProgressBar.Size = new Size(267, 19);6263 ClientSize = new Size(292, 53);64 Controls.Add(this._ProgressBar);65 Text = "Multithreading in Windows Forms";66 ResumeLayout(false);67 }68}
转载于:https://www.cnblogs.com/nanshouyong326/archive/2007/05/08/738667.html
转载请注明原文地址: https://win8.8miu.com/read-1483476.html