An async cancellable polling Task that waits between iterations
public class Foo { private const int TASK_ITERATION_DELAY_MS = 1000; private CancellationTokenSource _cts; public Foo() { this._cts = new CancellationTokenSource(); } public void StartExecution() { Task.Factory.StartNew(this.OwnCodeCancelableTask_EveryNSeconds, this._cts.Token); } public void CancelExecution() { this._cts.Cancel(); } /// <summary> /// "Infinite" loop that runs every N seconds. Good for checking for a heartbeat or updates. /// </summary> /// <param name="taskState">The cancellation token from our _cts field, passed in the StartNew call</param> private async void OwnCodeCancelableTask_EveryNSeconds(object taskState) { var token = (CancellationToken)taskState; while (!token.IsCancellationRequested) { Console.WriteLine("Do the work that needs to happen every N seconds in this loop"); // Passing token here allows the Delay to be cancelled if your task gets cancelled. await Task.Delay(TASK_ITERATION_DELAY_MS, token); } } }
An async cancellable polling Task that waits between iterations
Table Of Contents
2
Literals
18
Regex
19
DateTime
20
Arrays
22
Enum
23
Tuples
25
GUID
26
BigInteger
28
Looping
29
Iterators
30
IEnumerable
35
Dynamic type
37
Casting
41
Interfaces
47
Methods
52
Keywords
53
Recursion
57
Inheritance
58
Generics
62
Reflection
65
LINQ Queries
66
LINQ to XML
68
XmlDocument
69
XDocument
79
Diagnostics
80
Overflow
86
Properties
89
Events
93
Structs
94
Attributes
95
Delegates
97
Networking
102
Action Filters
103
Polymorphism
104
Immutability
105
Indexer
107
Stream
108
Timers
109
Stopwatches
110
Threading
112
Async Await
114
BackgroundWorker
115
Task Parallel Library
117
Lock Statement
118
Yield Keyword
121
Func delegates
124
ICloneable
125
IComparable
127
Using SQLite
128
Caching
129
Code Contracts
136
Pointers
144
Hash Functions
146
Cryptography
148
C# Script
149
Runtime Compile
150
Interoperability
156
Contributors