Skip to content

Commit 222d9f7

Browse files
committed
Added Threading package docs
1 parent 5912ec6 commit 222d9f7

1 file changed

Lines changed: 78 additions & 0 deletions

File tree

docs/articles/features/threading.md

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,3 +5,81 @@ title: Using the Threading package | MADE.NET
55

66
# Using the Threading package
77

8+
## Modernizing System.Threading.Timer with the MADE.Threading.Timer
9+
10+
Setting up and managing a `System.Threading.Timer` can sometimes be cumbersome. How do you control the start and stop state?
11+
12+
The `MADE.Threading.Timer` is a modern take on `System.Threading.Timer` providing properties for configuring the `Interval` and `DueTime`, plus an event handler for `Tick`.
13+
14+
It also includes simple methods to `Start` and `Stop` the timer running.
15+
16+
Below is an example of using the `MADE.Threading.Timer` to setup and start running a timed job.
17+
18+
```csharp
19+
public class TimerJob
20+
{
21+
private MADE.Threading.Timer processTimer;
22+
23+
public TimerJob()
24+
{
25+
processTimer = new MADE.Threading.Timer { Interval = TimeSpan.FromMinutes(1) };
26+
processTimer.Tick += OnProcessTimerTick;
27+
}
28+
29+
public void StartTimer()
30+
{
31+
processTimer.Start();
32+
}
33+
34+
public void StopTimer()
35+
{
36+
processTimer.Stop();
37+
}
38+
39+
40+
private void OnProcessTimerTick(object sender, object e)
41+
{
42+
// Do work.
43+
}
44+
}
45+
```
46+
47+
The equivalent for the `System.Threading.Timer` would look like
48+
49+
```csharp
50+
public class TimerJob
51+
{
52+
private System.Threading.Timer processTimer;
53+
54+
public void StartTimer()
55+
{
56+
if (processTimer == null)
57+
{
58+
processTimer = new System.Threading.Timer(
59+
c => this.OnProcessTimerTick(),
60+
null,
61+
0,
62+
(int)Math.Ceiling(TimeSpan.FromMinutes(1).TotalMilliseconds));
63+
}
64+
else
65+
{
66+
processTimer.Change(
67+
0,
68+
(int)Math.Ceiling(TimeSpan.FromMinutes(1).TotalMilliseconds));
69+
}
70+
}
71+
72+
public void StopTimer()
73+
{
74+
processTimer?.Change(Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan);
75+
}
76+
77+
78+
private void OnProcessTimerTick()
79+
{
80+
// Do work.
81+
}
82+
}
83+
```
84+
85+
As you can see, the MADE implementation performs the same actions, but is much more concise and a lot easier to understand.

0 commit comments

Comments
 (0)