Skip to content

Instantly share code, notes, and snippets.

@lucamilan
Created April 18, 2021 08:46
Show Gist options
  • Select an option

  • Save lucamilan/58384b26f2f91c8c9cf865e8860d52eb to your computer and use it in GitHub Desktop.

Select an option

Save lucamilan/58384b26f2f91c8c9cf865e8860d52eb to your computer and use it in GitHub Desktop.
Infinite Loop with Cancellation Token in C# Async fashoin way
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