Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <blockquote> <p>I have an event that when fired the subscribers execute some DB code that may take a while to return. I want to execute all the subscriber delegates in parallel. I am trying to use Parallel.Foreach but I cant get it quite right any suggestions?</p> </blockquote> <p>I would recommend pushing the parallelism into the subscriber's side, and not try to invoke the delegates in parallel.</p> <p>Just have the subscribers do:</p> <pre><code>private void OnMyEvent(object sender, EventArgs e) { Task.Factory.StartNew( () =&gt; { // Your DB code logic here... }); } </code></pre> <p>This will cause the event to occur asynchronously.</p> <p>If you must wait for the return type, I personally would avoid events all together. The issue here is that there is an inherent expectation that an event subscriber will not block. Allowing the event to block will violate expectations, and lead to problems. </p> <p>Instead, I would recommend using a form of inversion of control, and handling this via an interface instead of an event. This then becomes a somewhat different variation of the <a href="http://en.wikipedia.org/wiki/Observer_pattern" rel="nofollow">Observer Pattern</a> than standard event usage:</p> <pre><code>// Publisher side - add methods to add/remove "subscribers": public void AddListener(IDatabaseOperation op) { lock(syncObj) // thread safety may be an issue... this.listeners.Add(op); } private void OnEvent() { lock(syncObj) { Parallel.ForEach(this.listeners, l =&gt; l.DoOperation()); } } </code></pre> <hr> <p>If you must multithread your invocations on the publishing side, it can be done via:</p> <pre><code>private void RaiseMyEvent(MyEventArgs e) { var handler = this.TheEvent; if (handler != null) { var tasks = new List&lt;Task&gt;(); foreach(var yourEvent in handler.GetInvocationList().Cast&lt;EventHandler&lt;MyEventArgs&gt;()) tasks.Add(Task.Factory.StartNew( () =&gt; yourEvent(this, e))); // Optionally wait here... Removing the following makes this asynchronous Task.WaitAll(tasks.ToArray()); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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