Skip to content

Instantly share code, notes, and snippets.

@code-atom
Created October 17, 2016 12:29
Show Gist options
  • Save code-atom/1e8c442d10b3696ecce2dd621a0b47ab to your computer and use it in GitHub Desktop.
Save code-atom/1e8c442d10b3696ecce2dd621a0b47ab to your computer and use it in GitHub Desktop.
How to use Cancellation Token thread in Order to cancel its execution.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Threading
{
class Program
{
static void Main(string[] args)
{
CancellationTokenSource tokenSoruce = new CancellationTokenSource();
Thread t = new Thread(new ParameterizedThreadStart((x) => {
var cancellationToken = (CancellationToken)x;
while (true)
{
if (cancellationToken.IsCancellationRequested)
{
return;
}
Console.Write(">>**<<");
}
}));
t.Start(tokenSoruce.Token);
Thread.Sleep(TimeSpan.FromSeconds(6));
tokenSoruce.Cancel();
Console.ReadLine();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment