from MSDN
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 |
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Threading; namespace ThreadSafeWinControls { public partial class Form1 : Form { public Form1() { InitializeComponent(); } // This event handler creates a thread that calls a // Windows Forms control in an unsafe way. private void button1_Click(object sender, EventArgs e) { UnsafeCall(); SafeCall(); } //------------------ UnSafe call of controls... --------------------- private void UnsafeCall() { CheckForIllegalCrossThreadCalls = false; // Important, if true - exception will be raised Thread demoThread = new Thread(new ThreadStart(this.ThreadProcUnsafe)); demoThread.Start(); } private void ThreadProcUnsafe() { this.textBox1.Text = "This text was set unsafely."; } //------------------ Safe call of controls... --------------------- private delegate void SetTextCallback(string Amessage); // This event handler creates a thread that calls a // Windows Forms control in a thread-safe way. private void SafeCall() { Thread demoThread = new Thread(new ThreadStart(this.ThreadProcSafe)); demoThread.Start(); } // This method is executed on the worker thread and makes // a thread-safe call on the TextBox control. private void ThreadProcSafe() { this.SetText("This text was set safely."); } private void SetText(string text) { // InvokeRequired required compares the thread ID of the // calling thread to the thread ID of the creating thread. // If these threads are different, it returns true. if (this.textBox1.InvokeRequired) { SetTextCallback d = new SetTextCallback(SetText); this.Invoke(d, new object[] { text }); } else { this.textBox1.Text = text; } } } } |