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
|
public partial class Form1 : Form
{
public event EventHandler Tested;
public Form1()
{
InitializeComponent();
Tested += new EventHandler(Form1_Tested);
}
private void Form1_Tested(object sender, EventArgs e)
{
Text = "Test";
}
private void Form1_Shown(object sender, EventArgs e)
{
#region Test 1
// Works normal in GUI-Thread directly
Form1_Tested(this, EventArgs.Empty);
#endregion
#region Test 2
// Works in worker thread and throws GUI exception
// because of foreign thread access
new Thread(new ThreadStart(delegate()
{
OnTested(EventArgs.Empty);
})).Start();
#endregion
#region Test 3
// Works in worker thread and returns to GUI-Thread
// to throw the event, so no need in eventhandler
// to use Control.Invoke();
AsyncOperation asyncOp = AsyncOperationManager.CreateOperation(null);
new Thread(new ThreadStart(delegate()
{
asyncOp.Post(new SendOrPostCallback(delegate(object obj)
{
OnTested(EventArgs.Empty);
}), null);
})).Start();
#endregion
}
protected virtual void OnTested(EventArgs e)
{
EventHandler tmpHandler = Tested;
if (tmpHandler != null)
tmpHandler(this, e);
}
}
|