Parallel event handling in C#

2020-02-13 03:45发布

问题:

I’m developing a module that has to handle many events coming from an external system. I’ve to use a third party class providing an event (OnNewMessage) passing some parameters as input and two as output, each event require a bunch of time in order to be processed. I’d like to serve these events in a parallel way, in order to avoid blocking the caller and to process multiple request in parallel.

Here an example of my code:

void Init()
{
   provider.OnNewMessage += new OnMessageEventHandler(processEvent);
}

void processEvent(string xml, int …, out string resultXML, out string description)
{
   ...
}

Which is the best approach to do this in C# 3.5?

Thanks

回答1:

I would use a queue to store the events, and then consume that queue from a bounch of thread from the thread pool.



回答2:

Here is the modified answer:

you don't want to block the caller , and you also want the caller to wait for the output. Then I think what you need is a web service. You define a web service for the task. And the caller call the web service to get the result. Web services support parallel processing.

I suggest you to use WCF. WCF has a request/reply message pattern, where one endpoint requests data from a second endpoint. The second endpoint replies. WCF is such a big topic and I am sorry that I can't dive into the detail here. But you could easily start with this video. And here are more videos for you.

==================== below is the old answer ===================

You could start a new thread for each event:

void processEvent(string xml, int …, out string resultXML, out string description)
{
   new Thread(Handler).Start(xml);
}

void Handler(object xml)
{
    //do the actual work here
}

Each caller request will get responded by a thread immediately, so the caller will not be blocked. And each thread will quit automatically after finishing processing the request, so there will not be too many threads in your system.

This is just a simple solution. You might want to consider thread pooling in order to improve performance.