Created
June 7, 2018 02:05
-
-
Save dancrowley303/c762acb0ca7fc8b407c06e7561b6806c to your computer and use it in GitHub Desktop.
TPL Task waiting on CancellationToken or AutoResetEvent
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Threading; | |
using System.Threading.Tasks; | |
namespace cancelThis | |
{ | |
class Program | |
{ | |
static void WaitingOnCancellationToken() | |
{ | |
//I initially thought this was a good pattern, but having to catch the OperationCanceledException is not a good flow | |
//also you need to wait on the main thread after the the token signals the cancellation, because otherwise the task | |
//will likely be still running when you dispose of it | |
var cts = new CancellationTokenSource(2000); | |
var i = 0; | |
using (var countTask = Task.Run(() => | |
{ | |
while (!cts.IsCancellationRequested) | |
{ | |
Console.WriteLine($"count is {++i}"); | |
Thread.Sleep(500); | |
} | |
}, cts.Token)) | |
{ | |
try | |
{ | |
countTask.Wait(cts.Token); | |
} | |
catch (OperationCanceledException) | |
{ | |
} | |
Console.WriteLine($"state is {countTask.Status}"); | |
//ick | |
Thread.Sleep(500); | |
Console.WriteLine($"state is {countTask.Status}"); | |
} | |
} | |
static void WaitOnAutoResetEvent() | |
{ | |
//by using an AutoResetEvent, the task can signal when finished. Note that Mutex has thread affinity | |
var cts = new CancellationTokenSource(); | |
var i = 0; | |
var are = new AutoResetEvent(false); | |
using (var countTask = Task.Run(() => | |
{ | |
while (!cts.IsCancellationRequested) | |
{ | |
Console.WriteLine($"count is {++i}"); | |
Thread.Sleep(500); | |
} | |
are.Set(); | |
}, cts.Token)) | |
{ | |
countTask.Wait(2000, cts.Token); | |
cts.Cancel(); | |
are.WaitOne(); | |
Console.WriteLine($"state is {countTask.Status}"); | |
} | |
} | |
static void Main(string[] args) | |
{ | |
//WaitingOnCancellationToken(); | |
WaitOnAutoResetEvent(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment