Er van uitgaande dat je C# gebruikt, dit is meestal hoe ik het oplos.
Het is welliswaar een console voorbeeld, maar het werkt ook in forms en je kan evt. de class afschieten naar een andere thread zodat je UI ook bereikbaar blijft.
Houd alleen in het achterhoofd dat je een cross thread exception kan krijgen als je niet controleert op 'InvokeRequired' en dit afhandelt natuurlijk.
Events.cs
C#:
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
| namespace EventHandlerExample
{
using System;
public delegate void IsReportReadyHandler(object sender, ReportReadyEventArgs e);
public delegate void StatusReportHandler(object sender, ReportStatusEventArgs e);
public class Reporting
{
private IsReportReadyHandler OnReportIsReady;
private StatusReportHandler OnStatusReport;
public event IsReportReadyHandler IsReportReady
{
add
{
this.OnReportIsReady += value;
}
remove
{
this.OnReportIsReady -= value;
}
}
public event StatusReportHandler CurrentStatus
{
add
{
this.OnStatusReport += value;
}
remove
{
this.OnStatusReport -= value;
}
}
private void readyReport(object sender, ReportReadyEventArgs e)
{
if (this.OnReportIsReady != null) this.OnReportIsReady(sender, e);
}
private void ReadyReport(bool IsReady)
{
if (this.OnReportIsReady != null) this.OnReportIsReady(this, new ReportReadyEventArgs(IsReady));
}
private void statusReport(object sender, ReportStatusEventArgs e)
{
if (this.OnStatusReport != null) this.OnStatusReport(sender, e);
}
private void StatusReport(string Status)
{
if (this.OnStatusReport != null) this.OnStatusReport(this, new ReportStatusEventArgs(Status));
}
public void TimeConsumingMethod(int Count)
{
for (int i = 0; i < Count; i++)
{
StatusReport(string.Format("C = {0}", i));
ReadyReport(false);
}
ReadyReport(true);
}
}
public class ReportReadyEventArgs : EventArgs
{
public ReportReadyEventArgs(bool IsReportReady)
{
this.IsReportReady = IsReportReady;
}
public bool IsReportReady { get; private set; }
}
public class ReportStatusEventArgs : EventArgs
{
public ReportStatusEventArgs(string Status)
{
this.Status = Status;
}
public string Status { get; private set; }
}
} |
Program.cs
C#:
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
| using System;
namespace EventHandlerExample
{
class Program
{
static Reporting r;
static void Main(string[] args)
{
r = new Reporting();
r.IsReportReady += ReportingHandler;
r.CurrentStatus += StatusReportHandler;
r.TimeConsumingMethod(10);
Console.ReadKey();
}
private static void ReportingHandler(object sender, ReportReadyEventArgs e)
{
Console.WriteLine(string.Format("Done? {0}", e.IsReportReady));
}
private static void StatusReportHandler(object sender, ReportStatusEventArgs e)
{
Console.WriteLine(e.Status);
}
}
} |
Mocht er iets niet duidelijk zijn dan laat het mij weten!