在winfrom开发,经常会用到多线程来操作窗体控件,这时就用到Invoke()方法
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 WinformThreadDemo { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private delegate void showTimeDelegate(string strTime); /// <summary> /// 显示时间 /// </summary> private void ShowTime() { while (true) { TextShowTime(DateTime.Now.ToString("HH:mm:ss")); } } /// <summary> /// 在TextBox中显示时间(多线程中) /// </summary> /// <param name="strTime"></param> private void TextShowTime(string strTime) { if (txtTime.InvokeRequired) { showTimeDelegate dl = new showTimeDelegate(TextShowTime); this.Invoke(dl, new object[] { strTime }); } else { this.txtTime.Text = DateTime.Now.ToString("HH:mm:ss"); } } private void Form1_Load(object sender, EventArgs e) { //开启线程 Thread thread = new Thread(new ThreadStart(ShowTime)); thread.Start(); } } }