开发者

Ordered execute threads

开发者 https://www.devze.com 2023-01-11 13:25 出处:网络
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

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 ex开发者_Python百科ample 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
        }
    }
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号