Windows Forms And Threading Is Easy

Ever wanted to use threads and update the user interface without worry about the InvokeRequired thing? Use SynchronizationContext!

1 using System;
2 using System.Windows.Forms;
3 using System.Threading;
4
5 namespace WindowsFormAndThreadingIsEasy
6 {
7     public partial class Form1 : Form
8     {
9         private SynchronizationContext context;
10         private Thread myThread;
11         private event EventHandler myEvent;
12
13         public Form1()
14         {
15             InitializeComponent();
16
17             context = SynchronizationContext.Current;
18
19             myEvent += new EventHandler(Form1_myEvent);
20
21             myThread = new Thread(ThreadProc);
22             myThread.IsBackground = true;
23             myThread.Start();
24         }
25
26         private int i = 0;
27         void Form1_myEvent(object sender, EventArgs e)
28         {
29             i++;
30             textBox1.Text = i.ToString();
31         }
32
33         private void OnMyEvent(object state)
34         {
35             EventArgs e = state as EventArgs;
36             if (myEvent != null)
37                 myEvent(this, e);
38         }
39
40
41         private void ThreadProc()
42         {
43             while (true)
44             {
45                 Thread.Sleep(1000);
46
47                 if (context != null)
48                 {
49                     context.Post(new SendOrPostCallback(OnMyEvent), null);
50                 }
51                 else
52                 {
53                     OnMyEvent(null);
54                 }
55             }
56         }
57
58
59     }
60 }

Download Visual Studio 2005 Project. (unzip with 7-zip).

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>