using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Threading; namespace TestThread2 { public partial class Form1 : Form { private Thread t; private Label labelTest; private delegate void ChangeLabel(string str); public Form1() { InitializeComponent(); this.labelTest = new System.Windows.Forms.Label(); this.labelTest.AutoSize = true; this.labelTest.Location = new System.Drawing.Point(29, 23); this.labelTest.Size = new System.Drawing.Size(106, 13); this.labelTest.Text = "Label avant opération"; this.Controls.Add(this.labelTest); } private void button1_Click(object sender, EventArgs e) { t = new Thread(new ThreadStart(ThreadMethod)); t.Start(); } private void ThreadMethod() { this.Invoke(new ChangeLabel(ChangeLabelText), "Label après opération"); //les instuctions se trouvant ici seront appelées //une fois la méthode ChangeLabelText executée et terminée. MessageBox.Show("Invoke terminé"); } private void ChangeLabelText(string str) { labelTest.Text = str; Thread.Sleep(5000); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Threading; namespace TestThread2 { public partial class Form1 : Form { private Thread t; private Label labelTest; private delegate void ChangeLabel(string str); public Form1() { InitializeComponent(); this.labelTest = new System.Windows.Forms.Label(); this.labelTest.AutoSize = true; this.labelTest.Location = new System.Drawing.Point(29, 23); this.labelTest.Size = new System.Drawing.Size(106, 13); this.labelTest.Text = "Label avant opération"; this.Controls.Add(this.labelTest); } private void button1_Click(object sender, EventArgs e) { t = new Thread(new ThreadStart(ThreadMethod)); t.Start(); MessageBox.Show("This is the main thread"); } private void ThreadMethod() { Thread.Sleep(5000); this.Invoke(new ChangeLabel(ChangeLabelText), "Label après opération"); //les instuctions se trouvant ici seront appelées //une fois la méthode ChangeLabelText executée et terminée. MessageBox.Show("Invoke terminé"); } private void ChangeLabelText(string str) { labelTest.Text = str; }
Vous n’avez pas trouvé la réponse que vous recherchez ?
Posez votre question