Skip to content

Instantly share code, notes, and snippets.

@ruslander
Created March 26, 2015 15:23
Show Gist options
  • Save ruslander/f47ef3826be312008f93 to your computer and use it in GitHub Desktop.
Save ruslander/f47ef3826be312008f93 to your computer and use it in GitHub Desktop.
kill task on demand
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Terminator
{
class Program
{
static void Main(string[] args)
{
var cts = new CancellationTokenSource();
Print("Strting task");
var cfg = Task.Factory.StartNew(() =>
{
Print("Before sleep");
try
{
using (cts.Token.Register(Thread.CurrentThread.Abort))
{
// assume this is blocking call, an open socket
Thread.Sleep(5000000);
}
}
catch (ThreadAbortException)
{
Print("Aborted sleep");
}
}, cts.Token);
Print("Press any key to trigger cancel");
ReadKey();
// I wand to make this cancalations predictible
cts.Cancel();
Print("Task now is in state : " + cfg.Status);
ReadKey();
}
private static void ReadKey()
{
Console.ReadKey();
}
static void Print(string text)
{
Console.WriteLine(text);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment