Last active
March 23, 2017 23:15
-
-
Save alexandrebl/98d3bda48197fa4694185e731ea44405 to your computer and use it in GitHub Desktop.
C# .Net Task Cancellation Token Example
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 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