Advertisement
Guest User

Untitled

a guest
May 24th, 2019
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.66 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. using Xamarin.Forms;
  9. using Xamarin.Forms.Xaml;
  10.  
  11. namespace XamarinAsync
  12. {
  13. [XamlCompilation(XamlCompilationOptions.Compile)]
  14. public partial class Cenario2Page : ContentPage
  15. {
  16. public Cenario2Page()
  17. {
  18. InitializeComponent();
  19. }
  20.  
  21. private async void btnProcessar_Clicked(object sender, EventArgs e)
  22. {
  23. CancellationTokenSource CancelSource = new CancellationTokenSource();
  24. var token = CancelSource.Token;
  25.  
  26. Stopwatch watch = new Stopwatch();
  27.  
  28. watch.Start();
  29.  
  30. //Iniciando Task1 e Task2 paralelamente
  31. var Task1 = Tarefa(1700,token);
  32. var Task2 = Tarefa(2000, token);
  33.  
  34. var retorno = await Task.WhenAny(Task1, Task2);
  35.  
  36. //Enviando sinal de cancelamento.
  37. CancelSource.Cancel();
  38.  
  39. watch.Stop();
  40.  
  41. await DisplayAlert(
  42. "Tarefas Terminaram",
  43. $"Tempo:{watch.Elapsed}",
  44. "OK");
  45. }
  46. private async Task<int> Tarefa(int ms)
  47. {
  48. await Task.Delay(ms);
  49. return ms;
  50. }
  51. private async Task<int> Tarefa(int ms, CancellationToken token)
  52. {
  53. while (!token.IsCancellationRequested && ms > 0)
  54. {
  55. await Task.Delay(1, token);
  56. ms--;
  57. }
  58. if (token.IsCancellationRequested)
  59. return 0;
  60.  
  61. return ms;
  62. }
  63. }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement