<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:atom="https://www.w3.org/2005/Atom" xmlns:sy="https://purl.org/rss/1.0/modules/syndication/" xmlns:dc="https://purl.org/dc/elements/1.1/" xmlns:content="https://purl.org/rss/1.0/modules/content/" xmlns:wfw="https://wellformedweb.org/CommentAPI/" xmlns:slash="https://purl.org/rss/1.0/modules/slash/"
  version="2.0">
  <channel>
    <title>Trevor's Dev Blog</title>
    <atom:link
      href="https://docs.microsoft.com/archive/blogs/trevor/feed.xml"
      rel="self"
      type="application/rss+xml" />
    <link>https://docs.microsoft.com/archive/blogs/trevor/feed.xml</link>
    <description />
    <lastBuildDate>Wed, 17 Apr 2019 04:09:34 GMT</lastBuildDate>
    <language>en-US</language>
    <sy:updatePeriod>hourly</sy:updatePeriod>
    <sy:updateFrequency>1</sy:updateFrequency>
    <item>
      <title>C# events examined</title>
      <link>https://docs.microsoft.com/archive/blogs/trevor/c-events-examined</link>
      <pubDate>Sat, 23 Aug 2008 19:58:00 GMT</pubDate>
      <dc:creator><![CDATA[trevorr]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/trevor/2008/08/23/c-events-examined/</guid>
      <description><![CDATA[I recently ran into a threading bug involving adding handlers to events, and decided to take a...]]></description>
      <content:encoded><![CDATA[<P>I recently ran into a threading bug involving adding handlers to events, and decided to take a deeper look at the compiler-generated event accessors.</P>
<P>Suppose you create a class like this one:</P><PRE class=csharpcode><SPAN class=kwrd>using</SPAN> System;

<SPAN class=kwrd>class</SPAN> C
{
    <SPAN class=kwrd>public</SPAN> <SPAN class=kwrd>event</SPAN> EventHandler E;

    <SPAN class=kwrd>public</SPAN> <SPAN class=kwrd>void</SPAN> AddHandler()
    {
        E += Handler; <SPAN class=rem>// thread-safe?</SPAN>
    }

    <SPAN class=kwrd>public</SPAN> <SPAN class=kwrd>void</SPAN> Handler(<SPAN class=kwrd>object</SPAN> sender, EventArgs e)
    {
    }
}
</PRE>
<P>Is the statement in AddHandler thread-safe? I had heard that event accessors were thread-safe, but the truth is actually a bit more complicated.&nbsp;To find the answer, let's look at the code that actually gets generated for this class (or at least a C# rendering of the generated IL):</P><PRE class=csharpcode><SPAN class=kwrd>using</SPAN> System;
<SPAN class=kwrd>using</SPAN> System.Runtime.CompilerServices;

<SPAN class=kwrd>class</SPAN> C
{
    <SPAN class=kwrd>private</SPAN> EventHandler E;

    [MethodImpl(MethodImplOptions.Synchronized)]
    <SPAN class=kwrd>public</SPAN> <SPAN class=kwrd>void</SPAN> add_E(EventHandler handler)
    {
        E = (EventHandler)Delegate.Combine(E, handler);
    }

    [MethodImpl(MethodImplOptions.Synchronized)]
    <SPAN class=kwrd>public</SPAN> <SPAN class=kwrd>void</SPAN> remove_E(EventHandler handler)
    {
        E = (EventHandler)Delegate.Remove(E, handler);
    }

    <SPAN class=kwrd>public</SPAN> <SPAN class=kwrd>void</SPAN> AddHandler()
    {
        E = (EventHandler)Delegate.Combine(E, Handler);
    }

    <SPAN class=kwrd>public</SPAN> <SPAN class=kwrd>void</SPAN> Handler(<SPAN class=kwrd>object</SPAN> sender, EventArgs e)
    {
    }
}
</PRE>
<P>Two things are interesting about this generated code: 1) The add and remove accessors used by event consumers outside the class&nbsp;are Synchronized to provide thread safety, as explained in section 10.8.1 of the <A href="https://download.microsoft.com/download/3/8/8/388e7205-bc10-4226-b2a8-75351c669b09/CSharp%20Language%20Specification.doc" target=_blank mce_href="https://download.microsoft.com/download/3/8/8/388e7205-bc10-4226-b2a8-75351c669b09/CSharp%20Language%20Specification.doc">C# Language Specification 3.0</A>. 2) The AddHandler method uses the private delegate field rather than the add accessor, and therefore is not thread-safe. This second point is rather subtle, and is something I was only recently made aware of by an elusive&nbsp;threading bug&nbsp;in my code. (The C# language spec does mention this special case near the end of section 10.8.1: "Within the class X [which defines Ev], references to Ev are compiled to reference the hidden field __Ev instead".) AddHandler can be made thread-safe (with respect to itself and the generated accessors) by locking <TT>this</TT>:</P><PRE class=csharpcode>    <SPAN class=kwrd>public</SPAN> <SPAN class=kwrd>void</SPAN> AddHandler()
    {
        <SPAN class=kwrd>lock</SPAN> (<SPAN class=kwrd>this</SPAN>)
        {
            E += Handler;
        }
    }
</PRE>
<P>Incidentally, the "equivalent" code above is not entirely equivalent to the original code, in that it does not actually expose an event E that consumers can access using the += and -= operators. The closest you can get to equivalent source code is the following, which differs only from the compiler-generated code in that the compiler can name both the field and the event "E":</P><PRE class=csharpcode><SPAN class=kwrd>using</SPAN> System;
<SPAN class=kwrd>using</SPAN> System.Runtime.CompilerServices;

<SPAN class=kwrd>class</SPAN> C
{
    <SPAN class=kwrd>private</SPAN> EventHandler e;
    <SPAN class=kwrd>public</SPAN> <SPAN class=kwrd>event</SPAN> EventHandler E
    {
        [MethodImpl(MethodImplOptions.Synchronized)]
        <SPAN class=kwrd>add</SPAN> <SPAN class=rem>// generates 'public void add_E(EventHandler)'</SPAN>
        {
            e = (EventHandler)Delegate.Combine(e, <SPAN class=kwrd>value</SPAN>);
        }

        [MethodImpl(MethodImplOptions.Synchronized)]
        <SPAN class=kwrd>remove</SPAN> <SPAN class=rem>// generates 'public void remove_E(EventHandler)'</SPAN>
        {
            e = (EventHandler)Delegate.Remove(e, <SPAN class=kwrd>value</SPAN>);
        }
    }

    <SPAN class=kwrd>public</SPAN> <SPAN class=kwrd>void</SPAN> AddHandler()
    {
        e += Handler; <SPAN class=rem>// generates e = (EventHandler)Delegate.Combine(e, Handler);</SPAN>
    }

    <SPAN class=kwrd>public</SPAN> <SPAN class=kwrd>void</SPAN> Handler(<SPAN class=kwrd>object</SPAN> sender, EventArgs e)
    {
    }
}
</PRE>
<P>It's also interesting to note that if the AddHandler method was changed to use "E += Handler" instead of "e += Handler", the compiler would call add_E instead (since events with user-provided accessors are not "field-like events," as defined in the language spec).</P>]]></content:encoded>
    </item>
    <item>
      <title>C# Warning CS0067: The event 'event' is never used</title>
      <link>https://docs.microsoft.com/archive/blogs/trevor/c-warning-cs0067-the-event-event-is-never-used</link>
      <pubDate>Thu, 14 Aug 2008 23:21:00 GMT</pubDate>
      <dc:creator><![CDATA[trevorr]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/trevor/2008/08/14/c-warning-cs0067-the-event-event-is-never-used/</guid>
      <description><![CDATA[Suppose you're implementing&nbsp;an interface like the following, which contains some events you...]]></description>
      <content:encoded><![CDATA[<P>Suppose you're implementing&nbsp;an interface like the following, which contains some events you care about and some you don't:</P><PRE><FONT color=#0000ff>public</FONT> <FONT color=#0000ff>interface</FONT> <FONT color=#2b91af>I
</FONT>{
<FONT color=#0000ff>    event</FONT> <FONT color=#2b91af>EventHandler</FONT> Important;
<FONT color=#0000ff>    event</FONT> <FONT color=#2b91af>EventHandler</FONT> Unimportant;
}</PRE>
<P>Forgetting about "unimportant" details, you'd probably start your implementation like this:</P><PRE><FONT color=#0000ff>public</FONT> <FONT color=#0000ff>class</FONT> <FONT color=#2b91af>C</FONT><FONT size=+0> : </FONT><FONT color=#2b91af>I
</FONT>{
<FONT color=#0000ff>&nbsp;&nbsp;&nbsp; public</FONT> <FONT color=#0000ff>event</FONT> <FONT color=#2b91af>EventHandler</FONT> Important;
&nbsp; 
<FONT color=#0000ff>&nbsp;&nbsp;&nbsp; protected virtual void</FONT> OnImportant(<FONT color=#2b91af>EventArgs</FONT> e)
<FONT color=#0000ff>&nbsp;&nbsp;&nbsp; </FONT>{
<FONT color=#2b91af><FONT color=#0000ff>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </FONT>EventHandler</FONT> handler = <FONT color=#0000ff>this</FONT>.Important;
<FONT color=#0000ff>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if</FONT> (handler != <FONT color=#0000ff>null</FONT>)
<FONT color=#0000ff>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </FONT>{
<FONT color=#0000ff>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </FONT>handler(<FONT color=#0000ff>this</FONT>, e);
<FONT color=#0000ff>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </FONT>}
<FONT color=#0000ff>&nbsp;&nbsp;&nbsp; </FONT>}
}</PRE>
<P>Of course, if you compile at this point, you'll get an error like this:</P><PRE>error CS0535: 'C' does not implement interface member 'I.Unimportant'</PRE>
<P>Obviously you need to define an implementation for Unimportant, even if you don't use it. Fortunately, it is very easy to implement an event:</P><PRE><FONT color=#0000ff>public event</FONT> <FONT color=#2b91af>EventHandler</FONT> Unimportant;</PRE>
<P>The problem with this implementation is that, since it is not ever used, and yet has a non-trivial compiler-generated implementation (which tracks the list of active handlers), the compiler issues the following warning:</P><PRE>warning CS0067: The event 'C.Unimportant' is never used</PRE>
<P>The advice given by the <A class="" href="https://msdn.microsoft.com/en-us/library/858x0ycc.aspx" mce_href="https://msdn.microsoft.com/en-us/library/858x0ycc.aspx">compiler documentation</A> isn't very helpful in this case; it just says you need to use the event. Other than creating a bogus reference to the event (or using '#pragma warning disable 67' to disable the warning), what does the compiler expect us to do? The right answer is to be explicit about what you expect from the event, which in this case, is nothing:</P><PRE><FONT color=#0000ff>public event</FONT> <FONT color=#2b91af>EventHandler</FONT> Unimportant
{
<FONT color=#0000ff>&nbsp;&nbsp;&nbsp; add</FONT> { }
<FONT color=#0000ff>&nbsp;&nbsp;&nbsp; remove</FONT> { }
}</PRE>
<P>This will cleanly suppress the warning, as well as the extra compiler-generated implementation of a normal event. And as another added benefit, it prompts one to think about whether this do-nothing implementation is really the best implementation. For instance, if the event isn't so much unimportant as it is unsupported, such that clients that do&nbsp;rely on the functionality are likely to fail without it, it might be better to explicitly indicate the&nbsp;lack of support&nbsp;and fail fast by throwing an exception:</P><PRE><FONT color=#0000ff>public event</FONT> <FONT color=#2b91af>EventHandler</FONT> Unsupported
{
<FONT color=#0000ff>&nbsp;&nbsp;&nbsp; add</FONT> { <FONT color=#0000ff>throw new</FONT> <FONT color=#2b91af>NotSupportedException</FONT>(); }
<FONT color=#0000ff>&nbsp;&nbsp;&nbsp; remove</FONT> { }
}</PRE>
<P>Of course, an interface that can be usefully implemented without some parts of its functionality is sometimes an indication that the interface is not optimally cohesive and should be split into separate interfaces.</P>]]></content:encoded>
    </item>
    <item>
      <title>Introduction</title>
      <link>https://docs.microsoft.com/archive/blogs/trevor/introduction</link>
      <pubDate>Thu, 14 Aug 2008 23:10:00 GMT</pubDate>
      <dc:creator><![CDATA[trevorr]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/trevor/2008/08/14/introduction/</guid>
      <description><![CDATA[The purpose of this blog is simply to record and share little programming ideas, tips, and tricks...]]></description>
      <content:encoded><![CDATA[<P>The purpose of this blog is simply to record and share little programming ideas, tips, and tricks that I run across. Don't count on being awed by earth-shattering insights, but hopefully you'll find something here that saves you time or headaches. :-)</P>
<P>-Trevor Robinson</P>]]></content:encoded>
    </item>
  </channel>
</rss>