mercredi 14 décembre 2011
Multithreading in C# (Java relies on the same foundation though)
Par Nicolas, mercredi 14 décembre 2011 à 10:53 :: geek stuff
using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Threading; using System.Collections.Generic; using System.Diagnostics; ////// Summary description for JokeServer /// public static class MOTDServer { static QueueMessageQueue = new Queue (); static Random rng = new Random(); static Thread ProducerThread; static string[] Messages = { "A bird in the hand is worth two in the bush", "A rolling stone gathers no moss", "A penny saved is a penny earned", "I'd rather have a bottle in front of me than a frontal lobotomy", "When life hands you lemons, make lemonade" }; private static void Init() { ProducerThread = new Thread(ProduceMessages); ProducerThread.Priority = ThreadPriority.Lowest; ProducerThread.Start(); } public static string GetNextMessage() { if (ProducerThread == null) Init(); string retval = null; Monitor.Enter(MessageQueue); while(MessageQueue.Count == 0) Monitor.Wait(MessageQueue); retval = MessageQueue.Dequeue(); Monitor.Exit(MessageQueue); return retval; } static void ProduceMessages() { for (; ; ) { if (MessageQueue.Count == 0) { Monitor.Enter(MessageQueue); MessageQueue.Enqueue(Messages[rng.Next(Messages.Length)]); Monitor.Pulse(MessageQueue); Monitor.Exit(MessageQueue); } Thread.Sleep(rng.Next(5000) + 2000); Debug.WriteLine("finished waiting"); } } }