Un altro esempio
C# sull'uso della
Task Parallel Library (TPL), in particolare l'istruzione
Invoke.
Questa permette di avviare in parallelo più lavori (task) differenti (DoWork, DoWorkA e DoWorkB).
using System;
using System.Threading;
using System.Diagnostics;
using System.Threading.Tasks;
namespace SgartParallelInvoke
{
class Program
{
static void Main(string[] args)
{
Stopwatch timer = new Stopwatch();
string param = "esempio di passaggio parametri";
timer.Start();
Parallel.Invoke(
delegate() { DoWork(1); },
delegate() { DoWorkA(2); },
delegate() { DoWorkA(3); },
delegate() { DoWork(4); },
delegate() { DoWork(5); },
delegate() { DoWorkB(6, param); },
delegate() { DoWorkA(7); },
delegate() { DoWork(8); },
delegate() { DoWorkB(9, param); }
);
timer.Stop();
Console.WriteLine(string.Format("\nFinished...\nTotal time: {0}"
, timer.Elapsed));
Console.ReadKey(true);
}
static void DoWork(int i)
{
int pause = 500000000;
Console.WriteLine(string.Format("{0} begin", i));
Thread.SpinWait(pause);
Console.WriteLine(string.Format("{0} end", i));
}
static void DoWorkA(int i)
{
int pause = 400000000;
Console.WriteLine(string.Format("{0} begin A", i));
Thread.SpinWait(pause);
Console.WriteLine(string.Format("{0} end A", i));
}
static void DoWorkB(int i, string param)
{
int pause = 450000000;
Console.WriteLine(string.Format("{0} begin B - param: {1}", i, param));
Thread.SpinWait(pause);
Console.WriteLine(string.Format("{0} end B", i));
}
}
}
In questo esempio si vede anche l'uso della classe
Stopwatch per rilevare in modo preciso il tempo di elaborazione e la classe
SpinWait dell'oggetto
Thread. Quest'ultima permette di creare un carico per la cpu, eseguengo tanti cicli di cpu quanti sono indicati nel suo argomento (variabile pause).