views:

43

answers:

1

Hello everybody

I have an console application which interact another user interface. Interface sends commands and my application should to process them. It is important to keep listening my console application while processing and execute commands in ordered. So i listen interface on main thread and execute commands in another thread.

Below example is what i am trying and problem is execution threads are not ordered.

Second thing is i am using lock in ProcessCommand method but i am not sure it is safe or not. For example one more threads can be inside of ProcessCommand method so one was process in lock so other thread can change incoming input value. Am i right ? I did some test and that never happen but still suspicious about it.

What can be best solution ? Solution Can be threading or not threading.

class Program
{
    static object locker = new object();
    static void Main(string[] args)
    {
        while (true)
        {
            var input = Console.ReadLine();
            (new Thread(new ParameterizedThreadStart(ProcessCommand))).Start(input);
        }
        Console.ReadKey();
    }
    static void ProcessCommand(dynamic input)
    {
        lock (locker)
        {
            Console.WriteLine(input);
            //process incoming command
        }
    }
}
+4  A: 

You're starting a new thread for each line of input. That's why you can't guarantee the ordering.

Instead of that, create a queue which the "reader" can put lines into, and the "processor" can read from. Have one thread reading and one thread processing. I have some sample code in my threading tutorial for a producer/consumer queue, although it's very simplistic.

If you're using .NET 4 (which I guess you are given the use of dynamic) then Parallel Extensions makes this much easier using BlockingCollection<T> and IProducerConsumerCollection<T>. Today is your lucky day - Joe Albahari has made the Parallel Extensions part of C# 4 in a Nutshell public on his web site. Read through that and it should make everything much clearer. You may want to skip to the BlockingCollection<T> part, but it's all worth reading.

Jon Skeet
What about my lock implementation ? incoming command can change in lock when another thread enter method ?
Freshblood
@Freshblood: No, it's not going to change what each thread is processing... it's just forcing your threads to be serialized - only one is going to be active at a time, making it pointless having multiple threads in the first place.
Jon Skeet
I love that website. I have been using it as a reference for years.
Brian Gideon
@Jon Skeet - I have used monitor methods as in your sample and it works great.Thank you so much. It can be easy with Parallel extensions but i am just foreigner to it. That site is great resource about multithreading but reading it with low level english doesn't help enough unfortunality.
Freshblood