ThreadPoolShit

using System; using System.Collections.Generic; using System.Threading; namespace ThreadTest { class Program { //dones bruges til at tjekke hvornår en tråd er færdig public static ManualResetEvent[] dones; public static object lockObj; public static List<Thread> threads; static void Main(string[] args) { dones = new ManualResetEvent[30]; threads = new List<Thread>(); lockObj = new object(); for (int i = 0; i < 30; i++) { ThreadInfo info = new ThreadInfo(); info.Identity = i; info.Number = 100000000; //Sætter trådens færdig event til false dones[i] = new ManualResetEvent(false); //Sætter en ny tråd i kø til at blive kørt ThreadPool.QueueUserWorkItem(new WaitCallback(CalculateRandoms), info); } Console.WriteLine("Begin"); //Vent på alle trådene er færdige WaitHandle.WaitAll(dones); foreach (Thread thread in threads) { Console.WriteLine(thread.ThreadNumber + " : " + thread.Result); } Console.ReadKey(); } //Funktion som kører i tråde object s er ThreadInfo, men skal typecastes inde i funktionen public static void CalculateRandoms(Object s) { //Typecast info objectet ThreadInfo info = s as ThreadInfo; //Laver en ny random med et random seed Random rnd = new Random(Guid.NewGuid().GetHashCode()); int random = 0; for (int i = 0; i < info.Number; i++) { random = rnd.Next(100); } lock (lockObj) { threads.Add(new Thread() { ThreadNumber = info.Identity, Result = random }); dones[info.Identity].Set(); } Console.WriteLine(info.Identity); Console.WriteLine("Done"); } } //Object som bruges til at smide info ind i tråden public class ThreadInfo { public int Identity { get; set; } public int Number { get; set; } } //Object jeg gemmer resultat i og gemmer i en liste public class Thread { public int ThreadNumber { get; set; } public int Result { get; set; } } }
Threadpool example

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.