Off the record

Aller au contenu | Aller au menu | Aller à la recherche

mercredi 14 décembre 2011

Multithreading in C# (Java relies on the same foundation though)

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 Queue MessageQueue = 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");
        }
    }
}

C# - delegates and asynchronous programming


    // define the delegate needed for async calls below
    delegate List GetQuoteDelegate(DateTime dt);

    // Use Async invocation to request the quotes in parallel
    List[] GetQuotes(DateTime dt)
    {
        ReservationServices reservationService = new ReservationServices();
        List[] retval = new List[3];

        List getQuoteDelegates = new List();

        getQuoteDelegates.Add(reservationService.GetAirlineQuotes);
        getQuoteDelegates.Add(reservationService.GetCarRentalQuotes);
        getQuoteDelegates.Add(reservationService.GetHotelQuotes);

        CountdownEvent cde = new CountdownEvent(3);

        for(int i=0; i<3; i++)
        {
            int localI = i;
            GetQuoteDelegate getQuoteDelegate = getQuoteDelegates[i];
            getQuoteDelegate.BeginInvoke(dt,
                iar => {
                    retval[localI] = (List)getQuoteDelegate.EndInvoke(iar);
                    cde.Signal();
                }, 
                null
            );
        }

        // wait for all to be finished
        cde.Wait();

        return retval;
    }