问题
I'm attempting to monitor the status of many HPC jobs running in parallel in a single threaded program, I'm subscribing to events raised by OnJobState and when monitoring as few as three jobs event state changes will go missing and the job is stuck running.
I'm assuming I need a thread per job to catch all the events but I can't find any information about the limits of events subscripton in a single thread program.
I would have thought the .net platform would queue this all up but that doesn't appear to be the case.
回答1:
Events are synchronous by default. That means that the object that raises an event will continue its execution only after all event handlers finished their work. The event handlers will run on the same thread as the object that raises the event. That leads to the following conclusions:
- The .NET framework can't queue anything, because the events are raised one after another
- You should not do heavy computing in event handlers. If the events are fired in rapid succession, even moderate computing should be avoided.
- If you want queuing, you need to implement it yourself: In your event handler, add the info about the new event to a thread safe queue and process this queue from another thread.
回答2:
I made this question more general to remove the confusion over HPC, looks like I have no control over how my event hander is executed so I need to make it thread safe.
来源:https://stackoverflow.com/questions/7726684/c-sharp-event-subscription-limits-for-single-threaded-programs