Created
April 18, 2021 08:46
-
-
Save lucamilan/58384b26f2f91c8c9cf865e8860d52eb to your computer and use it in GitHub Desktop.
Infinite Loop with Cancellation Token in C# Async fashoin way
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
| public class Foo | |
| { | |
| private CancellationTokenSource _cts; | |
| public Foo() | |
| { | |
| this._cts = new CancellationTokenSource(); | |
| } | |
| public void StartExecution() | |
| { | |
| Task.Factory.StartNew(this.OwnCodeCancelableTask, this._cts.Token); | |
| } | |
| public void CancelExecution() | |
| { | |
| this._cts.Cancel(); | |
| } | |
| /// <summary> | |
| /// "Infinite" loop with no delays. Writing to a database while pulling from a buffer for example. | |
| /// </summary> | |
| /// <param name="taskState">The cancellation token from our _cts field, passed in the StartNew call</param> | |
| private void OwnCodeCancelableTask(object taskState) | |
| { | |
| var token = (CancellationToken) taskState; //Our cancellation token passed from StartNew(); | |
| while ( !token.IsCancellationRequested ) | |
| { | |
| Console.WriteLine("Do your task work in this loop"); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment