简体   繁体   中英

Implementing comunication between threads C#

I have Class1 which have event listener for messages from API. When signal is recieved I want to send this message to multiple other work threads, which process the message. What is the easyiest and fastest way to implement this in C#? Are there any good tutorials about this subject? My main concern is how to get incoming message as fast as possible to working threads, because they have to respond with their resault as fast as possible to the API.

Any help would be really welcome.

If the problem is as simple as you say it is, then I would use a Producer / Consumer pattern

Drop this into a new console app project to see it in action. Code is rough, but it should give you an idea.

class Program
{
    static BlockingCollection<string> _signalStore = new BlockingCollection<string>();

    static void Listener()
    {
        while(true)
        {
            var message = _signalStore.Take();
            Console.WriteLine(Thread.CurrentThread.ManagedThreadId + ": " + message);
        }
    }

    static void Sender()
    {
        var counter = 0;
        while(true)
        {
            _signalStore.Add(counter++.ToString());
            Thread.Sleep(100);
        }
    }

    static void Main(string[] args)
    {
        var listenerCount = 5;

        for (var i = 0;  i < listenerCount; i++)
        {
            var newListnerTask = new Task(Listener);
            newListnerTask.Start();
        }


        var newSenderTask = new Task(Sender);
        newSenderTask.Start();

        Console.ReadKey();
    }
}

You can use the producer/consumer pattern whereby your producer thread places data onto a queue and the consumers are alerted when something is on the queue and wake up to take the item of the queue.

The .NET framework BlockingCollections will help you implement this pattern.

您可以在Pub / Sub模式上使用MSDN文章http://msdn.microsoft.com/en-us/library/ff649664.aspx

The fastest respond is achieved if:

  • there is only one event for all consumers (so producer have to set only 1 event, not 100);
  • consumers are already waiting for it;

pseudo-implementation:

ManualResetEvent event = new ManualResetEvent(false);

// consumer 1
event.WaitOne();
// consumer 2
event.WaitOne();

// producer
event.Set();
event = new ManualResetEvent(false);

You could look into leveraging a messaging queue which provides an API for pub/sub. Some favorites out there are RabbitMQ ( http://www.rabbitmq.com/ ) and ActiveMQ ( http://activemq.apache.org/ )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM