Created
March 26, 2015 15:23
-
-
Save ruslander/f47ef3826be312008f93 to your computer and use it in GitHub Desktop.
kill task on demand
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 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