Skip to content

Instantly share code, notes, and snippets.

@alexandrebl
Last active March 23, 2017 23:15
Show Gist options
  • Select an option

  • Save alexandrebl/98d3bda48197fa4694185e731ea44405 to your computer and use it in GitHub Desktop.

Select an option

Save alexandrebl/98d3bda48197fa4694185e731ea44405 to your computer and use it in GitHub Desktop.
C# .Net Task Cancellation Token Example
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ApplicationTask.CancellationTokenExample {
/// <summary>
/// Classe
/// </summary>
class Program {
/// <summary>
/// Método principal
/// </summary>
/// <param name="args">Argumentos</param>
static void Main(string[] args) {
//Fonte de cancelamento
var cts = new CancellationTokenSource();
//Token
var token = cts.Token;
//Tarefa
var myTask1 = Task.Factory.StartNew(() => {
//Loop
for (var x = 0; x < 1000; x++) {
try {
//Cancela se houver o cancelamento do token
token.ThrowIfCancellationRequested();
//Immpre o valor de x
Console.WriteLine(x);
//Aguarda um segunda
Thread.Sleep(800);
} catch (Exception ex) {
//Imprime mensagem
Console.WriteLine("Processamento , task 1");
//Para o loop
break;
}
}
//Imprime mensagem
Console.WriteLine("Fim");
}, token);
//Tarefa
var myTask2 = Task.Factory.StartNew(() => {
//Loop
for (var x = 0; x < 1000; x++) {
//Cancela se houver o cancelamento do token
if (token.IsCancellationRequested) {
//Imprime mensagem
Console.WriteLine("Processamento interrompido, tarefa 2");
//Para o loop
break;
}
//Immpre o valor de x
Console.WriteLine(x);
//Aguarda um segunda
Thread.Sleep(1000);
}
//Imprime mensagem
Console.WriteLine("Fim tarefa 2");
}, token);
//Aguarda 5 segundos
Thread.Sleep(5000);
//Cacela a tarefa
cts.Cancel();
//Aguarda um tecla ser pressionada
Console.ReadKey();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment