Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If it feels wrong because events are more sophisticated and outward-facing than necessary for your internal communications (which I believe is at least partially true considering events can call multiple clients whereas you know you only need to notify one, right?), then I propose the following alternative. Instead of using events to communicate the completion of Foo to FooHandler, since Foo is internal anyway, you could add a callback parameter to the constructor or Load method of Foo, which Foo can call when it is done loading. This parameter can be just a function if you only have one callback, or it can be an interface if you have many. Here's how I think your code would look with the simplified internal interface:</p> <pre><code>public delegate void FooLoaded(FooHandler sender, EventArgs e); class Foo { Action&lt;Foo&gt; callback; /* ... some code ... */ public void Load(Action&lt;Foo&gt; callback) { this.callback = callback; load_asynchronously(); } public void callMeWhenLoadingIsDone() { callback(this); } } class FooHandler { public event FooLoaded OneFooLoaded; /* ... some code ... */ public void LoadAllFoos() { foreach (Foo f in FooList) { f.Load(foo_loaded); } } void foo_loaded(Foo foo) { // Create EventArgs based on values from foo if necessary OneFooLoaded(this, null); } } </code></pre> <p>Notice that this also allows you to be more strongly typed with the FooLoaded delegate.</p> <p>If, on the other hand, it feels wrong because the event shouldn't have to go through FooHandler to get to the client, then 1) I would dispute that because if the client doesn't want to deal with the individual Foo objects, it shouldn't be sinking events from them at that level either, and 2) If you really wanted to do that, you could implement some public callback interface on Foo even though Foo is private, or use a mechanism like Pavel suggested. I think, however, that clients like the simplicity of implementing fewer event handlers and distinguishing the source within the one handler rather than having to connect (and potentially disconnect) events from dozens of smaller objects.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload