Note that there are some explanatory texts on larger screens.

plurals
  1. POBoiler plate code replacement - is there anything bad about this code?
    primarykey
    data
    text
    <p>I've recently created these two (unrelated) methods to replace lots of boiler-plate code in my winforms application. As far as I can tell, they work ok, but I need some reassurance/advice on whether there are some problems I might be missing.</p> <p>(from memory)</p> <pre><code>static class SafeInvoker { //Utility to avoid boiler-plate InvokeRequired code //Usage: SafeInvoker.Invoke(myCtrl, () =&gt; myCtrl.Enabled = false); public static void Invoke(Control ctrl, Action cmd) { if (ctrl.InvokeRequired) ctrl.BeginInvoke(new MethodInvoker(cmd)); else cmd(); } //Replaces OnMyEventRaised boiler-plate code //Usage: SafeInvoker.RaiseEvent(this, MyEventRaised) public static void RaiseEvent(object sender, EventHandler evnt) { var handler = evnt; if (handler != null) handler(sender, EventArgs.Empty); } } </code></pre> <p>EDIT: See related question <a href="https://stackoverflow.com/questions/258409/how-to-get-information-about-an-exception-raised-by-the-target-of-controlinvoke">here</a></p> <p><strong>UPDATE</strong></p> <p>Following on from deadlock problems (related in <a href="https://stackoverflow.com/questions/2055960/control-invoke-getting-stuck-in-hidden-showdialog">this question</a>), I have switched from Invoke to BeginInvoke (see an explanation <a href="https://stackoverflow.com/questions/229554/whats-the-difference-between-invoke-and-begininvoke/229558#229558">here</a>).</p> <p><strong>Another Update</strong></p> <p>Regarding the second snippet, I am increasingly inclined to use the 'empty delegate' pattern, which fixes this problem 'at source' by declaring the event directly with an empty handler, like so:</p> <pre><code>event EventHandler MyEventRaised = delegate {}; </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.
 

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