Advertisement
fcamuso

Task - B

Jul 7th, 2021
1,266
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.50 KB | None | 0 0
  1. using System;
  2. using System.Threading;
  3. using System.Threading.Tasks;
  4.  
  5. namespace Task_A
  6. {
  7.   class Program
  8.   {
  9.  
  10.     static void MetodoGenerico()
  11.     {
  12.       //int n = 0;
  13.       //int a = 100 / n;
  14.  
  15.       for (int i = 0; i < 100; i++) Console.WriteLine(i);
  16.     }
  17.  
  18.     static int Sommatore(int[] v)
  19.     {
  20.       int somma = 0;
  21.       //int a = 100 / somma;
  22.  
  23.       foreach (int n in v) { somma += n; Thread.Sleep(100); }
  24.       return somma;
  25.     }
  26.  
  27.     static void Main(string[] args)
  28.     {
  29.       int[] v = { 1, 2, 3, 4 };
  30.  
  31.       //Task t1 = Task.Run(() => MetodoGenerico());
  32.  
  33.       //try
  34.       //{ t1.Wait(); }
  35.       //catch (AggregateException e)
  36.       //{
  37.       //  if (e.InnerException is DivideByZeroException)
  38.       //    Console.WriteLine("Intercettato tentativo da metodo generico di divisione per zero");
  39.       //}
  40.  
  41.  
  42.       Task<int> t2 = Task<int>.Run(() => Sommatore(v));
  43.      
  44.       var aw = t2.GetAwaiter();
  45.  
  46.       aw.OnCompleted(() => Task.Run(() => MetodoGenerico()));
  47.      
  48.  
  49.       while (true)
  50.       {
  51.         Console.WriteLine($"Stato: {t2.Status}");
  52.         if (t2.Status == TaskStatus.RanToCompletion || t2.IsFaulted) break;
  53.         Thread.Sleep(50);
  54.       }
  55.  
  56.       try
  57.       { Console.WriteLine(t2.Result); }
  58.       catch(AggregateException e)
  59.       {
  60.         if (e.InnerException is DivideByZeroException)
  61.           Console.WriteLine("Intercettato tentativo di divisione per zero");
  62.       }
  63.  
  64.  
  65.      
  66.  
  67.       Console.WriteLine("main terminato");
  68.     }
  69.   }
  70. }
  71.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement