Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET events - blocking subscribers from subscribing on an event

Let's say I have a "Processor" interface exposing an event - OnProcess. Usually the implementors do the processing. Thus I can safely subscribe on this event and be sure it will be fired. But one processor doesn't do processing - thus I want to prevent subscribers to subscibe on it. Can I do that? In other words in the code below I want the last line to throw an exception:

var emptyProcessor = new EmptyProcessor();
emptyProcessor.OnProcess += event_handler; // This line should throw an exception.
like image 974
Moshe Avatar asked Feb 17 '10 17:02

Moshe


People also ask

Which is the best place to subscribe event handler to an event?

To subscribe to events by using the Visual Studio IDEOn top of the Properties window, click the Events icon. Double-click the event that you want to create, for example the Load event. Visual C# creates an empty event handler method and adds it to your code. Alternatively you can add the code manually in Code view.

Are event handlers blocking?

Events are blocking (meaning that they run synchronously with the thread that calls them).

How to use event handler in C#?

In C#, event handler will take the two parameters as input and return the void. The first parameter of the Event is also known as the source, which will publish the object. The publisher will decide when we have to raise the Event, and the subscriber will determine what response we have to give.

Why use event handler in C#?

An event handler, in C#, is a method that contains the code that gets executed in response to a specific event that occurs in an application. Event handlers are used in graphical user interface (GUI) applications to handle events such as button clicks and menu selections, raised by controls in the user interface.


1 Answers

class EmptyProcessor : IProcessor {

    [Obsolete("EmptyProcessor.OnProcess should not be directly accessed", true)]
    public event EventHandler OnProcess { 
        add { throw new NotImplementedException(" :( "); }
        remove { }
    }
}

In this situation, the true parameter on Obsolete causes a compile-time exception. so:

EmptyProcessor processor1 = new EmptyProcessor();
IProcessor processor2 = new EmptyProcessor();

processor1.OnProcess += handler;  // <-- compile-time error
processor2.OnProcess += handler;  // <-- run-time error
like image 170
Jimmy Avatar answered Sep 30 '22 08:09

Jimmy