Basic MSMQ example

ClassLibrary project

public class Command1
{
    public int id { get; set; }
    public string name { get; set; }
}
static string queue = @".private$Command1Queue";

Client project

static void Main(string[] args)
{
    MessageQueue msMq = new MessageQueue(queue);
    while (true)
    {
        var key = Console.ReadKey();
        switch (key.Key)
        {
            case ConsoleKey.Escape:
                return;
            default:
                string name = "SomeName";
                for (int i = 0; i < 1000; i++)
                {
                    Command1 command = new Command1()
                    {
                        id = i,
                        name = name
                    };
                    msMq.Send(command);
                    Console.WriteLine("id: " + command.id + ", name: " + command.name);
                }
                break;
        }
    }
}

Service project

static void Main(string[] args)
{
    while (true)
    {
        CancellationTokenSource cancelToken = new CancellationTokenSource();
        Process(cancelToken.Token);
        Console.ReadKey();
        Console.WriteLine("Cancelling ...");
        cancelToken.Cancel();
        Console.WriteLine("Cancelled ...");
        if (Console.ReadKey().Key == ConsoleKey.Escape) return;
    }
}
private static void Process(CancellationToken token)
{
    Task.Factory.StartNew(() =>
    {
        while (true)
        {
            int msgCount = 0;
            ParallelOptions options = new ParallelOptions();
            options.MaxDegreeOfParallelism = 15;
            options.CancellationToken = token;

            Parallel.ForEach(Enumerable.Range(0, 15), options, (i) =>
            {
                MessageQueue msMq = new MessageQueue(queue);
                msMq.Formatter = new XmlMessageFormatter(new Type[] { typeof(Command1) });
                try
                {
                    Message msg = msMq.Receive(TimeSpan.Zero);
                    var message = (Command1)msg.Body;
                    Console.WriteLine("id: " + message.id + ", name: " + message.name);
                    Thread.Sleep(10);
                    Interlocked.Increment(ref msgCount);
                }
                catch (MessageQueueException mqex)
                {
                    if (mqex.MessageQueueErrorCode == MessageQueueErrorCode.IOTimeout)
                        return; // nothing in queue
                    else throw;
                }
            });
            if (msgCount < 15) //the queue is empty
            {
                MessageQueue msMq = new MessageQueue(queue);
                msMq.Peek();
            }
        }
    });
}