I am developing a component which needs to process the live feed and broadcast the data to the listeners in pretty fast manner ( with about 100 nano second level accuracy, even less than that if I can do that) Currently I am raising an event from my code which subscriber can subscribe to. However because in C# event handlers run on the same thread which raises the event, my thread which raises the event will be blocked until all subscribers finish processing the event. I do not have control on subscribers' code, so they can possibly do any time consuming operations in event handler, which may block the thread which is broadcasting.
What can I do so that I can broadcast the data to other subscribers but can still broadcast the stuff quite fast??
It seems like you are looking for tasks. The following is an extension method i wrote for my job that can asynchronously invokes an event so that every event handler is on their own thread. I can't comment on its speed since that has never been a requirement for me.
UPDATE
Based on the comments i adjusted it so that only one task is created to call all of the subscribers
I can't speak to if this will reliably meet the 100ns requirement but here's an alternative where you'd provide the end user with a way to provide you a ConcurrentQueue that you would fill and they could listen to on a separate thread.
Since given the fact that you can't hold up processing on other listeners this means multiple threads. Having dedicated listening threads on the listeners seems like a reasonable approach to try, and the concurrent queue seems like a decent delivery mechanism. In this implementation it's just constantly polling, but you could probably use thread signaling to reduce the cpu load using something like
AutoResetEvent
.100 ns is a very tough target to hit. I believe it will take a deep understanding of what you're doing and why to hit that kind of performance.
However, asynchronously invoking event subscribers is pretty easy to solve. It's already answered here by, who else, Jon Skeet.
edit: I should also mention that you need to be running on a real-time operating system to give tight performance guarantees to your users.
You can use these simple extension methods on your event handlers:
Usage:
The
cancellationToken
is necessary to guaranteeStartNew()
actually uses a different thread, as explained here.