<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>pc &#187; C#</title>
	<atom:link href="http://projectcoho.com/?cat=3&#038;feed=rss2" rel="self" type="application/rss+xml" />
	<link>http://projectcoho.com</link>
	<description>Just another WordPress site</description>
	<lastBuildDate>Sun, 22 Jan 2012 01:26:07 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>WeakAction, or delegates with a weak reference to their target</title>
		<link>http://projectcoho.com/?p=67</link>
		<comments>http://projectcoho.com/?p=67#comments</comments>
		<pubDate>Mon, 11 Apr 2011 02:54:51 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Code Review]]></category>
		<category><![CDATA[Coding]]></category>
		<category><![CDATA[Contracting]]></category>
		<category><![CDATA[Software Design]]></category>

		<guid isPermaLink="false">http://www.codeneverwritten.com/2011/04/10/weakaction-or-delegates-with-a-weak-reference-to-their-target/</guid>
		<description><![CDATA[Abstract: Thoughts on implementing an Action-type delegate that holds only a weak reference to the target object. Background I recently started evaluating MVVM libraries for my client’s project. Though I often share parts of my own unpublished library with a &#8230; <a href="http://projectcoho.com/?p=67">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><em><font size="2">Abstract: Thoughts on implementing an </font></em><a href="http://msdn.microsoft.com/en-us/library/system.action.aspx" target="_blank"><em><font size="2">Action</font></em></a><em><font size="2">-type delegate that holds only a weak reference to the target object.</font></em></p>
<h3>Background</h3>
<p>I recently started evaluating MVVM libraries for my client’s project. Though I often share parts of my own unpublished library with a client I had inherited this project and it already had it&#8217;s share of commonly-used MVVM types. What it lacked, and I added, was a quickie &quot;message bus&quot; implementation. Not the distributed, enterprise-class sort of message bus, but an intra-app messaging service that decouples senders from receivers. It&#8217;s the message bus that I really wanted to replace with a more robust, tested version that must surely already exist in one of the established MVVM libraries.</p>
<p>As luck would have it the first library I downloaded touted a messaging service but, as is too often the case, you get what you pay for. After perusing the code for a bit I could see that the messaging functionality wasn&#8217;t thread-safe, a feature I require. My app is a multi-threaded WPF app with both managed and native threads and takes pains to keep work off the UI thread in order to achieve smooth and somewhat real-time rendering of data. Wrapping the library’s messaging code for synchronization would be easy, but it doesn&#8217;t feel like fine enough granularity of locking for good performance.</p>
<h3>Weak Action is Weak</h3>
<p>Another driver in looking for an established library is that my quickie message bus implementation holds references to subscribed listeners. Not really a problem unless a listener fails to unsubscribe, in this case the listener will never be garbage collected. I consider that an undesirable situation. So I took a look at the above library&#8217;s implementation of a weak action; I quickly saw that this code used not a weak reference but a strong reference; it suffered the very problem it purported to fix. FYI, I did verify that the problem is known to the library&#8217;s author.</p>
<p>Now, at this time I haven&#8217;t finished evaluating libraries, and this was a bit of a rough start. Maybe I’ll just set aside some time to come up with a solution myself. Like&#8230; now.</p>
<h3>An Elegant Solution (maybe&#8230;)</h3>
<p>The problem I&#8217;d like to solve is that Action holds a reference to the target object of non-static delegates, preventing that target from being GC&#8217;d. The most elegant solution would allow me to simply replace my use of Action and Action&lt;T&gt; with an implementation that holds only a weak reference to the target. And here it is:</p>
<div style="border-bottom: silver 1px solid; text-align: left; border-left: silver 1px solid; padding-bottom: 4px; line-height: 10pt; background-color: #f4f4f4; margin: 20px 0px 10px; padding-left: 4px; width: 97.5%; padding-right: 4px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; max-height: 200px; font-size: 8pt; overflow: auto; border-top: silver 1px solid; cursor: text; border-right: silver 1px solid; padding-top: 4px" id="codeSnippetWrapper">
<div style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: #f4f4f4; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px" id="codeSnippet">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum1">   1:</span> <span style="color: #0000ff">static</span> Action CreateWeakAction(Action action)</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum2">   2:</span> {</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum3">   3:</span>     <span style="color: #0000ff">if</span> (action == <span style="color: #0000ff">null</span>)</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum4">   4:</span>         <span style="color: #0000ff">throw</span> <span style="color: #0000ff">new</span> ArgumentNullException(<span style="color: #006080">&quot;action&quot;</span>);</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum5">   5:</span>&#160; </pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum6">   6:</span>     <span style="color: #008000">// If it's a static delegate there's no need to create a weak reference.</span></pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum7">   7:</span>     <span style="color: #0000ff">if</span> (action.Target == <span style="color: #0000ff">null</span>)</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum8">   8:</span>         <span style="color: #0000ff">return</span> action;</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum9">   9:</span>&#160; </pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum10">  10:</span>     Type type = action.GetType();</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum11">  11:</span>     WeakReference targetRef = <span style="color: #0000ff">new</span> WeakReference(action.Target);</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum12">  12:</span>     MethodInfo method = action.Method;</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum13">  13:</span>&#160; </pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum14">  14:</span>     <span style="color: #0000ff">return</span> () =&gt;</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum15">  15:</span>         {</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum16">  16:</span>             <span style="color: #008000">// Don't reference 'action' in this lambda expression.</span></pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum17">  17:</span>             <span style="color: #0000ff">object</span> target = targetRef.Target;</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum18">  18:</span>             <span style="color: #0000ff">if</span> (target == <span style="color: #0000ff">null</span>)</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum19">  19:</span>             {</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum20">  20:</span>                 <span style="color: #008000">// Target was GC'd; don't do anything. (Ick.)</span></pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum21">  21:</span>             }</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum22">  22:</span>             <span style="color: #0000ff">else</span></pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum23">  23:</span>             {</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum24">  24:</span>                 Delegate.CreateDelegate(type, target, method).DynamicInvoke();</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum25">  25:</span>             }</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum26">  26:</span>         };</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum27">  27:</span> }</pre>
<p><!--CRLF--></div>
</div>
<p>Using CreateWeakAction is pretty easy:</p>
<div style="border-bottom: silver 1px solid; text-align: left; border-left: silver 1px solid; padding-bottom: 4px; line-height: 10pt; background-color: #f4f4f4; margin: 20px 0px 10px; padding-left: 4px; width: 97.5%; padding-right: 4px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; max-height: 200px; font-size: 8pt; overflow: auto; border-top: silver 1px solid; cursor: text; border-right: silver 1px solid; padding-top: 4px" id="codeSnippetWrapper">
<div style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: #f4f4f4; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px" id="codeSnippet">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum1">   1:</span> Action action = CreateWeakAction(() =&gt; receiver.DoSomething(42));</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum2">   2:</span> <span style="color: #008000">// Time passes...</span></pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum3">   3:</span> action();</pre>
<p><!--CRLF--></div>
</div>
<p>Now the target (‘receiver’ in the above example) is free to be collected, but I have a new Action delegate returned from CreateWeakAction that will not be collected unless I release my reference to it. More than that, I have no way of telling whether the delegate I&#8217;m holding no longer has a live reference to the target. I could conceivably change my Action to a Func&lt;&gt; that returns an indicator of whether the target was GC&#8217;d, but that would require me to actually call the delegate to determine its state. And I would lose the elegant drop-in replacement I was hoping for.</p>
<h3>A More Measured Solution</h3>
<p>Setting aside my personal desire for elegance solutions, the actual requirements I&#8217;m looking to satisfy in my message bus are twofold: 1) don&#8217;t hold a reference to the target listener and 2) don&#8217;t hold unnecessary objects in the heap. A weak action implementation that satisfies these needs might look something like this:</p>
<div style="border-bottom: silver 1px solid; text-align: left; border-left: silver 1px solid; padding-bottom: 4px; line-height: 10pt; background-color: #f4f4f4; margin: 20px 0px 10px; padding-left: 4px; width: 97.5%; padding-right: 4px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; max-height: 200px; font-size: 8pt; overflow: auto; border-top: silver 1px solid; cursor: text; border-right: silver 1px solid; padding-top: 4px" id="codeSnippetWrapper">
<div style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: #f4f4f4; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px" id="codeSnippet">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum1">   1:</span> <span style="color: #0000ff">class</span> WeakAction</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum2">   2:</span> {</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum3">   3:</span>     <span style="color: #0000ff">public</span> WeakAction(Action action);</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum4">   4:</span>     <span style="color: #0000ff">public</span> <span style="color: #0000ff">bool</span> IsTargetAlive { get; }</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum5">   5:</span>     <span style="color: #0000ff">public</span> WeakActionInvocationResult Invoke();</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum6">   6:</span> }</pre>
<p><!--CRLF--></div>
</div>
<p>This would allow me to create an instance of my weak action, invoke it&#8217;s behavior when needed, and check whether the target is still alive so that I can cull stale instances from my message bus implementation. And, thanks to an uninterrupted morning at my local coffee joint I have what I wanted. You may note that I&#8217;ve made an abstraction for invoking instance delegates; this makes that code more easily reusable for generic implementations (e.g., WeakAction&lt;T&gt;).</p>
<div style="border-bottom: silver 1px solid; text-align: left; border-left: silver 1px solid; padding-bottom: 4px; line-height: 10pt; background-color: #f4f4f4; margin: 20px 0px 10px; padding-left: 4px; width: 97.5%; padding-right: 4px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; max-height: 200px; font-size: 8pt; overflow: auto; border-top: silver 1px solid; cursor: text; border-right: silver 1px solid; padding-top: 4px" id="codeSnippetWrapper">
<div style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: #f4f4f4; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px" id="codeSnippet">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum1">   1:</span> <span style="color: #0000ff">internal</span> <span style="color: #0000ff">class</span> WeakAction</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum2">   2:</span> {</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum3">   3:</span>     <span style="color: #0000ff">private</span> <span style="color: #0000ff">readonly</span> InvocationAgent _instanceAction;</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum4">   4:</span>     <span style="color: #0000ff">private</span> <span style="color: #0000ff">readonly</span> Action _staticAction;</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum5">   5:</span>&#160; </pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum6">   6:</span>     <span style="color: #0000ff">public</span> WeakAction(Action action)</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum7">   7:</span>     {</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum8">   8:</span>         <span style="color: #0000ff">if</span> (action == <span style="color: #0000ff">null</span>)</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum9">   9:</span>             <span style="color: #0000ff">throw</span> <span style="color: #0000ff">new</span> ArgumentNullException(<span style="color: #006080">&quot;action&quot;</span>);</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum10">  10:</span>&#160; </pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum11">  11:</span>         <span style="color: #0000ff">if</span> (action.Target != <span style="color: #0000ff">null</span>)</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum12">  12:</span>         {</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum13">  13:</span>             _instanceAction = <span style="color: #0000ff">new</span> InvocationAgent(action);</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum14">  14:</span>         }</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum15">  15:</span>         <span style="color: #0000ff">else</span></pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum16">  16:</span>         {</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum17">  17:</span>             _staticAction = action;</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum18">  18:</span>         }</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum19">  19:</span>&#160; </pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum20">  20:</span>         Debug.Assert(_instanceAction == <span style="color: #0000ff">null</span> || _staticAction == <span style="color: #0000ff">null</span>);</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum21">  21:</span>         Debug.Assert(!(_instanceAction == <span style="color: #0000ff">null</span> &amp;&amp; _staticAction == <span style="color: #0000ff">null</span>));</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum22">  22:</span>     }</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum23">  23:</span>&#160; </pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum24">  24:</span>     <span style="color: #0000ff">public</span> <span style="color: #0000ff">bool</span> IsTargetAlive { get { <span style="color: #0000ff">return</span> IsStatic || _instanceAction.IsTargetAlive; } }</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum25">  25:</span>&#160; </pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum26">  26:</span>     <span style="color: #0000ff">private</span> <span style="color: #0000ff">bool</span> IsStatic { get { <span style="color: #0000ff">return</span> _staticAction != <span style="color: #0000ff">null</span>; } }</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum27">  27:</span>&#160; </pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum28">  28:</span>     <span style="color: #0000ff">public</span> WeakActionInvocationResult Invoke()</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum29">  29:</span>     {</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum30">  30:</span>         <span style="color: #0000ff">if</span> (_instanceAction != <span style="color: #0000ff">null</span>)</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum31">  31:</span>             <span style="color: #0000ff">return</span> _instanceAction.Invoke();</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum32">  32:</span>&#160; </pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum33">  33:</span>         _staticAction();</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum34">  34:</span>         <span style="color: #0000ff">return</span> WeakActionInvocationResult.Invoked;</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum35">  35:</span>     }</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum36">  36:</span> }</pre>
<p><!--CRLF--></div>
</div>
<p>Note that I’ve made an optimization for static delegates—there’s no need to incur the cost of dynamic invocation in that case because a static delegate has no target, therefore it won’t prevent anything from being GC’d.</p>
<p>Now imagine we have a messaging implementation that needs to track listeners with Action delegates but would rather not keep a reference to listeners forever if they happen not to unsubscribe. We can now create an instance of WeakAction and use it to invoke the listener&#8217;s Action when we wish; we can also query the WeakAction on occasion to determine whether it still has a live listener.</p>
<p>Finally here are the missing parts to make it work, the interesting bits. What makes this work is pulling apart the delegate into its component parts, holding the target part with a&#160; weak reference, and reassembling the parts into a delegate only when needed to invoke the original delegate. No reference to the original delegate is held.</p>
<div style="border-bottom: silver 1px solid; text-align: left; border-left: silver 1px solid; padding-bottom: 4px; line-height: 10pt; background-color: #f4f4f4; margin: 20px 0px 10px; padding-left: 4px; width: 97.5%; padding-right: 4px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; max-height: 200px; font-size: 8pt; overflow: auto; border-top: silver 1px solid; cursor: text; border-right: silver 1px solid; padding-top: 4px" id="codeSnippetWrapper">
<div style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: #f4f4f4; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px" id="codeSnippet">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum1">   1:</span> <span style="color: #0000ff">internal</span> <span style="color: #0000ff">enum</span> WeakActionInvocationResult</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum2">   2:</span> {</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum3">   3:</span>     Invoked,</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum4">   4:</span>     Collected,</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum5">   5:</span> }</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum6">   6:</span>&#160; </pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum7">   7:</span> <span style="color: #0000ff">internal</span> <span style="color: #0000ff">class</span> InvocationAgent</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum8">   8:</span> {</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum9">   9:</span>     <span style="color: #0000ff">private</span> <span style="color: #0000ff">readonly</span> Type _type;</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum10">  10:</span>     <span style="color: #0000ff">private</span> <span style="color: #0000ff">readonly</span> WeakReference _targetRef;</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum11">  11:</span>     <span style="color: #0000ff">private</span> <span style="color: #0000ff">readonly</span> MethodInfo _method;</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum12">  12:</span>&#160; </pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum13">  13:</span>     <span style="color: #0000ff">public</span> InvocationAgent(Delegate action)</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum14">  14:</span>     {</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum15">  15:</span>         Debug.Assert(action.Target != <span style="color: #0000ff">null</span>, <span style="color: #006080">&quot;Expected a non-static delegate&quot;</span>);</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum16">  16:</span>&#160; </pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum17">  17:</span>         _type = action.GetType();</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum18">  18:</span>         _targetRef = <span style="color: #0000ff">new</span> WeakReference(action.Target);</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum19">  19:</span>         _method = action.Method;</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum20">  20:</span>     }</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum21">  21:</span>&#160; </pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum22">  22:</span>     <span style="color: #0000ff">public</span> <span style="color: #0000ff">bool</span> IsTargetAlive { get { <span style="color: #0000ff">return</span> _targetRef.IsAlive; } }</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum23">  23:</span>&#160; </pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum24">  24:</span>     <span style="color: #0000ff">public</span> WeakActionInvocationResult Invoke(<span style="color: #0000ff">params</span> <span style="color: #0000ff">object</span>[] args)</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum25">  25:</span>     {</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum26">  26:</span>         <span style="color: #0000ff">object</span> target = _targetRef.Target;</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum27">  27:</span>         <span style="color: #0000ff">if</span> (target == <span style="color: #0000ff">null</span>)</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum28">  28:</span>             <span style="color: #0000ff">return</span> WeakActionInvocationResult.Collected;</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum29">  29:</span>&#160; </pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum30">  30:</span>         <span style="color: #008000">// Don't keep a reference to this delegate.</span></pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum31">  31:</span>         Delegate.CreateDelegate(_type, target, _method).DynamicInvoke(args);</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum32">  32:</span>         <span style="color: #0000ff">return</span> WeakActionInvocationResult.Invoked;</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum33">  33:</span>     }</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum34">  34:</span> }</pre>
<p><!--CRLF--></div>
</div>
<p>I&#8217;ll leave it as an interesting challenge to the reader to implement WeakAction&lt;T&gt;. Here’s what it might look like:</p>
<div style="border-bottom: silver 1px solid; text-align: left; border-left: silver 1px solid; padding-bottom: 4px; line-height: 10pt; background-color: #f4f4f4; margin: 20px 0px 10px; padding-left: 4px; width: 97.5%; padding-right: 4px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; max-height: 200px; font-size: 8pt; overflow: auto; border-top: silver 1px solid; cursor: text; border-right: silver 1px solid; padding-top: 4px" id="codeSnippetWrapper">
<div style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: #f4f4f4; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px" id="codeSnippet">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum1">   1:</span> <span style="color: #0000ff">class</span> WeakAction&lt;T&gt;</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum2">   2:</span> {</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum3">   3:</span>     <span style="color: #0000ff">public</span> WeakAction(Action&lt;T&gt; action);</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum4">   4:</span>     <span style="color: #0000ff">public</span> <span style="color: #0000ff">bool</span> IsTargetAlive { get; }</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum5">   5:</span>     <span style="color: #0000ff">public</span> WeakActionInvocationResult Invoke(T t);</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 10pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum6">   6:</span> }</pre>
<p><!--CRLF--></div>
</div>
<p>Grab a cup of coffee and have at it. <img src='http://projectcoho.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  Please note: I’ve tested only on the desktop CLR, not Silverlight or Phone, so caveat emptor.</p>
]]></content:encoded>
			<wfw:commentRss>http://projectcoho.com/?feed=rss2&#038;p=67</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Where Did My Object Go? Part 2</title>
		<link>http://projectcoho.com/?p=7</link>
		<comments>http://projectcoho.com/?p=7#comments</comments>
		<pubDate>Mon, 03 Dec 2007 20:18:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[CLR]]></category>
		<category><![CDATA[Code Review]]></category>
		<category><![CDATA[Coding]]></category>
		<category><![CDATA[Software Design]]></category>

		<guid isPermaLink="false">http://projectcoho.com/?p=7</guid>
		<description><![CDATA[In Part 1 of this article I discussed the possibility of an object instance being collected before a method returns in this scenario:  new MyObject().LongRunningMethod(); as well as this scenario:  MyObject o = new MyObject(); o.LongRunningMethod(); Here we&#8217;ll discuss how &#8230; <a href="http://projectcoho.com/?p=7">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>In <a href="http://www.codeneverwritten.com/2007/12/where-did-my-object-go-part-1.html" target="_blank">Part 1</a> of this article I discussed the possibility of an object instance being collected before a method returns in this scenario: </p>
<pre class="code">    <span style="color: #0000ff;">new</span> <span style="color: #2b91af;">MyObject</span>().LongRunningMethod();</pre>
<p>as well as this scenario: </p>
<pre class="code">    <span style="color: #2b91af;">MyObject</span> o = <span style="color: #0000ff;">new</span> <span style="color: #2b91af;">MyObject</span>();    o.LongRunningMethod();</pre>
<p>Here we&#8217;ll discuss how this could become a problem. Frankly, it&#8217;s pretty easy to cause the problem, but I think it generally involves some ugliness on the part of software design or implementation, largely involving clean-up of fields when the instance is finalized. </p>
<h3>Don&#8217;t Try This at Home</h3>
<p>I don&#8217;t think it&#8217;s likely you&#8217;ll see a lot of code that does this, but here&#8217;s one way to run afoul of your object going way: export a reference to a field that the object cleans up when it&#8217;s finalized. You can export the reference, say, by making that field visible through a property. Exposing a field that you&#8217;re going to clean up in the finalizer would be an easy way to create a coupling between your object and other (arbitrary) client code that has no knowledge of your object&#8217;s life span. </p>
<h3>Call Stack Antics</h3>
<p>Another way to invoke the potential problem is to lose your &#8220;this&#8221; reference on the call stack. The code below manages to lose the &#8220;this&#8221; reference by passing a field to the helper method rather than allowing the helper to access the field directly via its own &#8220;this&#8221; reference. When the helper tries to access <span style="font-family: Courier New;">fs.Length</span> an <span style="font-family: Courier New;">ObjectDisposedException</span> is thrown. </p>
<p>Why does this throw? Well, the last live reference to the instance was lost when <span style="font-family: Courier New;">LongRunningMethod</span> passed <span style="font-family: Courier New;">_input</span> to <span style="font-family: Courier New;">Helper</span>. Essentially we&#8217;ve again exported the field value from the instance and no longer hold a reference to the instance, allowing the GC to finalize it. <span style="font-family: Courier New;">Helper</span> is left holding a reference to an object that has been finalized. </p>
<p><a href="http://11011.net/software/vspaste"></a><strong>Note:</strong> Again, you will not see this behavior in a debug build. When running code marked as &#8220;debug&#8221; the JITter <a href="http://blogs.msdn.com/yunjin/archive/2005/05/15/417569.aspx" target="_blank">extends the lifetime</a> of the local object to the end of the method. So you will not see this effect if you&#8217;ve compiled with the /debug flag. </p>
<pre class="code">    <span style="color: #0000ff;">using</span> System;    <span style="color: #0000ff;">using</span> System.IO;

    <span style="color: #008000;">// Ugliness ensues.
</span>    <span style="color: #0000ff;">sealed</span> <span style="color: #0000ff;">class</span> <span style="color: #2b91af;">MyUglyObject
</span>    {
        <span style="color: #0000ff;">public</span> MyUglyObject(<span style="color: #0000ff;">string</span> inputPath)
        {
            <span style="color: #008000;">// Real production code would likely not delete the file when done...
</span>            <span style="color: #008000;">// ...but this is a sample app.
</span>            _input = <span style="color: #0000ff;">new</span> <span style="color: #2b91af;">FileStream</span>(<span style="color: #2b91af;">Path</span>.GetTempFileName(), <span style="color: #2b91af;">FileMode</span>.Open, <span style="color: #2b91af;">FileAccess</span>.Read, <span style="color: #2b91af;">FileShare</span>.Read);
        }

        ~MyUglyObject()
        {
            <span style="color: #0000ff;">if</span> (_input != <span style="color: #0000ff;">null</span>)
            {
                _input.Close();
                _input = <span style="color: #0000ff;">null</span>;
            }
        }

        <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">void</span> LongRunningMethod()
        {
            Helper(_input); <span style="color: #008000;">// Our last reference to 'this' (implicit).
</span>        }

        <span style="color: #0000ff;">private</span> <span style="color: #0000ff;">void</span> Helper(<span style="color: #2b91af;">FileStream</span> fs)
        {
            <span style="color: #008000;">// A long-running method can easily experience a garbage collection
</span>            <span style="color: #008000;">// before returning. This one happens for force it to occur.
</span>            <span style="color: #2b91af;">GC</span>.Collect();
            <span style="color: #2b91af;">GC</span>.WaitForPendingFinalizers();

            <span style="color: #008000;">// Ka-boom!
</span>            <span style="color: #0000ff;">long</span> inputSize = fs.Length;
            <span style="color: #008000;">// ...
</span>        }

        <span style="color: #0000ff;">private</span> <span style="color: #2b91af;">FileStream</span> _input;
    }

    <span style="color: #0000ff;">class</span> <span style="color: #2b91af;">Program
</span>    {
        <span style="color: #0000ff;">static</span> <span style="color: #0000ff;">void</span> Main(<span style="color: #0000ff;">string</span>[] args)
        {
            <span style="color: #0000ff;">new</span> <span style="color: #2b91af;">MyUglyObject</span>(<span style="color: #a31515;">@"....readme.txt"</span>).LongRunningMethod();
        }
    }</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<h3>Can You See It?</h3>
<p>As you can see above it takes a bit of effort to cause the code to blow up. If <span style="font-family: Courier New;">Helper</span> had used <span style="font-family: Courier New;">_input.Length</span> instead of taking a parameter the problem would not exist. </p>
<p>But, what I find a bit creepy about the above code is that if <span style="font-family: Courier New;">Helper</span> were a static method it would seem respectable: </p>
<pre class="code">    <span style="color: #0000ff;">private</span> <span style="color: #0000ff;">static</span> <span style="color: #0000ff;">void</span> Helper(<span style="color: #2b91af;">FileStream</span> fs)
    {
        <span style="color: #008000;">// A long-running method can easily experience a garbage collection
</span>        <span style="color: #008000;">// before returning. This one happens for force it to occur.
</span>        <span style="color: #2b91af;">GC</span>.Collect();
        <span style="color: #2b91af;">GC</span>.WaitForPendingFinalizers();

        <span style="color: #008000;">// Ka-boom!
</span>        <span style="color: #0000ff;">long</span> inputSize = fs.Length;
        <span style="color: #008000;">// ...
</span>    }</pre>
<p><a href="http://11011.net/software/vspaste"></a>At first glance it now looks like helper is a normal static helper function, as is likely seen in code bases across the world. It doesn&#8217;t need a &#8220;this&#8221; reference, it takes a reference to the object it uses, everything appears fine on the surface. Would you see the &#8220;this&#8221; reference being lost by the code calling <span style="font-family: Courier New;">Helper</span> in a code review? I&#8217;m not so sure I would have until recently. </p>
<div id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:5ab9e4f3-aaea-4ce5-83ea-be553bd2b340" class="wlWriterSmartContent" style="display: inline; margin: 0px; padding: 0px;">Technorati tags: <a rel="tag" href="http://technorati.com/tags/Coding">Coding</a>, <a rel="tag" href="http://technorati.com/tags/Software%20Design">Software Design</a>, <a rel="tag" href="http://technorati.com/tags/CLR">CLR</a>, <a rel="tag" href="http://technorati.com/tags/C#">C#</a>, <a rel="tag" href="http://technorati.com/tags/Code%20Review">Code Review</a></div>
<div class="blogger-post-footer"><img src="https://blogger.googleusercontent.com/tracker/19212077-4548100263884978316?l=www.codeneverwritten.com" alt="" width="1" height="1" /></div>
]]></content:encoded>
			<wfw:commentRss>http://projectcoho.com/?feed=rss2&#038;p=7</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Where Did My Object Go? Part 1</title>
		<link>http://projectcoho.com/?p=8</link>
		<comments>http://projectcoho.com/?p=8#comments</comments>
		<pubDate>Mon, 03 Dec 2007 19:14:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[CLR]]></category>
		<category><![CDATA[Code Review]]></category>
		<category><![CDATA[Coding]]></category>
		<category><![CDATA[Software Design]]></category>

		<guid isPermaLink="false">http://projectcoho.com/?p=8</guid>
		<description><![CDATA[I ran across this scenario a few months ago and was just reminded of it. It takes a bit of an edge case to make it a problem, but it&#8217;s interesting all the same. There&#8217;s a regular idiom in C# &#8230; <a href="http://projectcoho.com/?p=8">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I ran across this scenario a few months ago and was just <a href="http://channel9.msdn.com/ShowPost.aspx?PostID=362232#362232" target="_blank">reminded</a> of it. It takes a bit of an edge case to make it a problem, but it&#8217;s interesting all the same.</p>
<p>There&#8217;s a regular idiom in C# in which we call a method on an object instance that we&#8217;ve created inline:</p>
<pre class="code">    <span style="color: #0000ff;">new</span> <span style="color: #2b91af;">MyObject</span>().LongRunningMethod();</pre>
<p>There assumption may be an assumption that the lifetime of this instance of <span style="color: #2b91af;"><span style="font-family: Courier New;">MyObject</span></span> extends at least until <span style="font-family: Courier New;">LongRunningMethod</span> returns, but this isn&#8217;t necessarily true. This same assumption is often made about local references to objects:</p>
<pre class="code">    <span style="color: #2b91af;">MyObject</span> o = <span style="color: #0000ff;">new</span> <span style="color: #2b91af;">MyObject</span>();    o.LongRunningMethod();</pre>
<p><a href="http://11011.net/software/vspaste"></a>However, in both these cases the object instance may be collected before <span style="font-family: Courier New;">LongRunningMethod</span> returns.</p>
<h3>Does this really happen?</h3>
<p>Yes, it can and does. The code below exercises this behavior. When you run it you will see the following output, indicating that the object was collected and finalized before <span style="font-family: Courier New;">LongRunningMethod</span> returns:</p>
<p><span style="font-family: Courier New; color: #008000;">    Using release build<br />
</span><span style="font-family: Courier New; color: #008000;">    Inline<br />
    Entering MyObject1.LongRunningMethod().<br />
    Finalizing in ~MyObject1().<br />
    Returning from MyObject1.LongRunningMethod(). </span><span style="font-family: Courier New; color: #008000;">    Local reference<br />
    Entering MyObject1.LongRunningMethod().<br />
    Finalizing in ~MyObject1().<br />
    Returning from MyObject1.LongRunningMethod().</span><strong>Note:</strong> You will not see this behavior in a debug build. When running code marked as &#8220;debug&#8221; the JITter <a href="http://blogs.msdn.com/yunjin/archive/2005/05/15/417569.aspx" target="_blank">extends the lifetime</a> of the local object to the end of the method. So you will <span style="text-decoration: underline;">not</span> see this effect if you&#8217;ve compiled with the /debug flag.</p>
<p>Note also that this article also assumes we&#8217;re using CLR 2.0. Future versions could obviously behavior differently.</p>
<p>Here&#8217;s the code. Just drop it into <span style="font-family: Courier New;">test.cs</span>, run <span style="font-family: Courier New;">csc test.cs</span>, and execute <span style="font-family: Courier New;">test.exe</span>.</p>
<pre class="code">    <span style="color: #0000ff;">using</span> System;

    <span style="color: #0000ff;">sealed</span> <span style="color: #0000ff;">class</span> <span style="color: #2b91af;">MyObject
</span>    {
        ~MyObject()
        {
            <span style="color: #2b91af;">Console</span>.WriteLine(<span style="color: #a31515;">"Finalizing in ~MyObject1()."</span>);
        }

        <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">void</span> LongRunningMethod()
        {
            <span style="color: #2b91af;">Console</span>.WriteLine(<span style="color: #a31515;">"Entering MyObject1.LongRunningMethod()."</span>);

            <span style="color: #008000;">// A long-running method can easily experience a garbage collection
</span>            <span style="color: #008000;">// before returning. This one happens for force it to occur.
</span>            <span style="color: #2b91af;">GC</span>.Collect();
            <span style="color: #2b91af;">GC</span>.WaitForPendingFinalizers();

            <span style="color: #2b91af;">Console</span>.WriteLine(<span style="color: #a31515;">"Returning from MyObject1.LongRunningMethod()."</span>);
        }
    }

    <span style="color: #0000ff;">class</span> <span style="color: #2b91af;">Program
</span>    {
        <span style="color: #0000ff;">static</span> <span style="color: #0000ff;">void</span> Main(<span style="color: #0000ff;">string</span>[] args)
        {
<span style="color: #0000ff;">    #if</span> DEBUG
<span style="color: #808080;">            string build = "debug";
</span><span style="color: #0000ff;">    #else
</span>            <span style="color: #0000ff;">string</span> build = <span style="color: #a31515;">"release"</span>;
<span style="color: #0000ff;">    #endif
</span>            <span style="color: #2b91af;">Console</span>.WriteLine(<span style="color: #a31515;">"Using {0} build"</span>, build);

            <span style="color: #008000;">// Try it both ways.

</span>            <span style="color: #2b91af;">Console</span>.WriteLine(<span style="color: #a31515;">"Inline"</span>);
            <span style="color: #0000ff;">new</span> <span style="color: #2b91af;">MyObject</span>().LongRunningMethod();

            <span style="color: #2b91af;">Console</span>.WriteLine();
            <span style="color: #2b91af;">Console</span>.WriteLine(<span style="color: #a31515;">"Local reference"</span>);
            <span style="color: #2b91af;">MyObject</span> o = <span style="color: #0000ff;">new</span> <span style="color: #2b91af;">MyObject</span>();
            o.LongRunningMethod();
        }
    }</pre>
<h3>Is this a problem?</h3>
<p>Generally, I&#8217;d say it&#8217;s not a problem. Once it has begun execution, <span style="font-family: Courier New;">LongRunningMethod</span> doesn&#8217;t need the original object reference unless it&#8217;s making reference to that instance. In that case the GC won&#8217;t be able to collect the object.</p>
<p>I&#8217;ll discuss how to make it a problem in <a href="http://www.codeneverwritten.com/2007/12/where-did-my-object-go-part-2.html" target="_blank">Part 2</a> of this article.</p>
<div id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:24332e3e-fe71-48b6-a509-a0c9cac22dcd" class="wlWriterSmartContent" style="display: inline; margin: 0px; padding: 0px;">Technorati tags: <a rel="tag" href="http://technorati.com/tags/Coding">Coding</a>, <a rel="tag" href="http://technorati.com/tags/Software%20Design">Software Design</a>, <a rel="tag" href="http://technorati.com/tags/CLR">CLR</a>, <a rel="tag" href="http://technorati.com/tags/C#">C#</a></div>
<div class="blogger-post-footer"><img src="https://blogger.googleusercontent.com/tracker/19212077-7952922260633718206?l=www.codeneverwritten.com" alt="" width="1" height="1" /></div>
]]></content:encoded>
			<wfw:commentRss>http://projectcoho.com/?feed=rss2&#038;p=8</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>C#: Type issues with ref parameters</title>
		<link>http://projectcoho.com/?p=12</link>
		<comments>http://projectcoho.com/?p=12#comments</comments>
		<pubDate>Thu, 15 Feb 2007 22:09:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://projectcoho.com/?p=12</guid>
		<description><![CDATA[I&#8217;ve witnessed a few instances where programmers have tripped up on types when using C#&#8217;s ref parameters. Here&#8217;s a post illustrating this. The temptation is to think that because one can assign a derived type to a base type reference that the &#8230; <a href="http://projectcoho.com/?p=12">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve witnessed a few instances where programmers have tripped up on types when using C#&#8217;s <span style="font-family: Courier New;">ref</span> parameters. Here&#8217;s <a title="Casting error in VS2005" href="http://channel9.msdn.com/ShowPost.aspx?PostID=283089" target="_blank">a post illustrating this</a>. The temptation is to think that because one can assign a derived type to a base type reference that the same should work with C#&#8217;s <span style="font-family: Courier New; color: #000080;">ref</span> and <span style="font-family: Courier New; color: #000080;">out</span> parameters.</p>
<p>It doesn&#8217;t. It&#8217;s simply not type safe.</p>
<h3>The Problem</h3>
<p>Here are the types from the above-mentioned post; I&#8217;ve added the <span style="font-family: Courier New;">FavoriteColor</span> property for later discussion:</p>
<div style="font-size: 10pt; background: white; color: black; font-family: courier new;">
<p style="margin: 0px;">    <span style="color: blue;">public</span> <span style="color: blue;">class</span> <span style="color: #2b91af;">Contact</span></p>
<p style="margin: 0px;">    {</p>
<p style="margin: 0px;">    }</p>
<p style="margin: 0px;"> </p>
<p style="margin: 0px;">    <span style="color: blue;">public</span> <span style="color: blue;">class</span> <span style="color: #2b91af;">Recipient</span> : <span style="color: #2b91af;">Contact</span></p>
<p style="margin: 0px;">    {</p>
<p style="margin: 0px;">        <span style="color: blue;">public</span> <span style="color: blue;">string</span> FavoriteColor { <span style="color: blue;">get</span> { <span style="color: blue;">return</span> <span style="color: #a31515;">&#8220;Alice Blue&#8221;</span>; } }</p>
<p style="margin: 0px;">    }</p>
</div>
<p>For discussion&#8217;s sake, here&#8217;s the declaration of the method in question:</p>
<div style="font-size: 10pt; background: white; color: black; font-family: courier new;">
<p style="margin: 0px;">    <span style="color: blue;">bool</span> FetchContact(<span style="color: blue;">ref</span> <span style="color: #2b91af;">Contact</span> contact, <span style="color: blue;">uint</span> row);</p>
</div>
<p><span style="font-family: Courier New;">FetchContact</span>&#8216;s signature indicates that it can return a <span style="font-family: Courier New;">Contact</span> via the <span style="font-family: Courier New;">contact</span> parameter.</p>
<p>And now the code the poster wants to use:</p>
<div style="font-size: 10pt; background: white; color: black; font-family: courier new;">
<p style="margin: 0px;">    <span style="color: #2b91af;">Recipient</span> recipient = <span style="color: blue;">new</span> <span style="color: #2b91af;">Recipient</span>();</p>
<p style="margin: 0px;">    FetchContact(<span style="color: blue;">ref</span> (<span style="color: #2b91af;">Contact</span>)recipient, row);</p>
</div>
<p>It certainly appears that the calling code desires to get a <span style="font-family: Courier New;">Recipient</span> from the call to <span style="font-family: Courier New;">FetchContact</span>, but that&#8217;s not within the interface contract of <span style="font-family: Courier New;">FetchContact</span>. <span style="font-family: Courier New;">FetchContact</span> returns a <span style="font-family: Courier New;">Contact </span>via its <span style="font-family: Courier New;">contact ref</span> parameter.</p>
<h3>Try, Try Again</h3>
<p>Now, it&#8217;s true that the following fragment of code works; it adheres to the interface contract specified by <span style="font-family: Courier New;">FetchContact</span>:</p>
<div style="font-size: 10pt; background: white; color: black; font-family: courier new;">
<p style="margin: 0px;">    <span style="color: #2b91af;">Recipient</span> recipient = <span style="color: blue;">new</span> <span style="color: #2b91af;">Recipient</span>();</p>
<p style="margin: 0px;">    <span style="color: #2b91af;">Contact</span> contact = recipient;</p>
<p style="margin: 0px;">    <span style="color: #2b91af;">Fetcher</span>.FetchContact(<span style="color: blue;">ref</span> contact, row);</p>
</div>
<p>Well, of course that works, we&#8217;ve modified the code to pass a <span style="font-family: Courier New;">ref Contact</span> as specified by the method signature. But why doesn&#8217;t the first?</p>
<h3>Type Safety</h3>
<p>Let&#8217;s try a different tack. To simplify, ignore for the moment that we&#8217;re looking at a <span style="font-family: Courier New;">ref</span> parameter. Instead, consider it an <span style="font-family: Courier New;">out</span> parameter. And we&#8217;ll also assume that there are more types derived from <span style="font-family: Courier New;">Contact</span>, for example:</p>
<div style="font-size: 10pt; background: white; color: black; font-family: courier new;">
<p style="margin: 0px;">    <span style="color: blue;">public</span> <span style="color: blue;">class</span> <span style="color: #2b91af;">Sender</span> : <span style="color: #2b91af;">Contact</span></p>
<p style="margin: 0px;">    {</p>
<p style="margin: 0px;">    }</p>
</div>
<p>Now, consider again, what type <span style="font-family: Courier New;">FetchContact</span> is returning here as an <span style="font-family: Courier New;">out</span> parameter?</p>
<div style="font-size: 10pt; background: white; color: black; font-family: courier new;">
<p style="margin: 0px;">    <span style="color: #2b91af;">Contact</span> contact = recipient;</p>
<p style="margin: 0px;">    <span style="color: #2b91af;">Fetcher</span>.FetchContact(<span style="color: blue;">out</span> contact, row);</p>
</div>
<p>The correct answer is &#8220;We&#8217;re not sure.&#8221; <span style="font-family: Courier New;">FetchContact</span> could return a <span style="font-family: Courier New;">Contact</span>, a <span style="font-family: Courier New;">Recipient</span>, a <span style="font-family: Courier New;">Sender</span>, or any other type derived from <span style="font-family: Courier New;">Contact</span>. The problem of the original code is that it assumes that <span style="font-family: Courier New;">FetchContact</span> is returning a <span style="font-family: Courier New;">Recipient</span> and tries to coerce the type. This would not be typesafe as we don&#8217;t know that the object returned is actually a <span style="font-family: Courier New;">Recipient</span>.</p>
<p>Consider what happens when <span style="font-family: Courier New;">FetchContact</span> is (legally) implemented like this:</p>
<div style="font-size: 10pt; background: white; color: black; font-family: courier new;">
<p style="margin: 0px;">    <span style="color: blue;">bool</span> FetchContact(<span style="color: blue;">out</span> <span style="color: #2b91af;">Contact</span> contact, <span style="color: blue;">uint</span> row)</p>
<p style="margin: 0px;">    {</p>
<p style="margin: 0px;">        contact = <span style="color: blue;">new</span> <span style="color: #2b91af;">Sender</span>();</p>
<p style="margin: 0px;">        <span style="color: blue;">return</span> <span style="color: blue;">true</span>;</p>
<p style="margin: 0px;">    }</p>
</div>
<p>The object passed back to the caller is obviously a <span style="font-family: Courier New;">Sender</span>, not a <span style="font-family: Courier New;">Recipient</span>. The only way for the caller to treat the returned value as a <span style="font-family: Courier New;">Recipient</span> is to break type safety, and C# generally does not let one do this.</p>
<h3>Hypothetically Speaking&#8230;</h3>
<p>What if C# did let us ignore type safety? Let&#8217;s suppose that this code could compile and execute:</p>
<div style="font-size: 10pt; background: white; color: black; font-family: courier new;">
<p style="margin: 0px;">    <span style="color: #2b91af;">Recipient</span> recipient = <span style="color: blue;">new</span> <span style="color: #2b91af;">Recipient</span>();</p>
<p style="margin: 0px;">    <span style="color: #2b91af;">Fetcher</span>.FetchContact(<span style="color: blue;">out</span> (<span style="color: #2b91af;">Contact</span>)recipient, row);</p>
<p style="margin: 0px;"> </p>
<p style="margin: 0px;">    <span style="color: blue;">string</span> fave = recipient.FavoriteColor;</p>
</div>
<p>Now <span style="font-family: Courier New;">FetchContact</span> has returned a <span style="font-family: Courier New;">Sender</span> that we&#8217;ve coerced into a <span style="font-family: Courier New;">Recipient</span> reference. Not good. It might execute right up until we use the <span style="font-family: Courier New;">FavoriteColor</span> property. Think about it. <span style="font-family: Courier New;">FetchContact</span> returns an instance of <span style="font-family: Courier New;">Sender</span>, which we&#8217;re treating as a <span style="font-family: Courier New;">Recipient</span>. But the <span style="font-family: Courier New;">Sender</span> type doesn&#8217;t have a FavoriteColor property. What would happen then? It would surely crash or return invalid data, just as we would see in C++.</p>
<p>C# prefers type safety and doesn&#8217;t allow this to happen. That&#8217;s a good thing.</p>
<h3>But it&#8217;s a ref, Not an out Parameter</h3>
<p>I believe this is the cause of the confusion around this issue. <span style="font-family: Courier New;">ref</span> parameters are both <span style="font-family: Courier New;">in</span> and <span style="font-family: Courier New;">out</span> parameters. Noone would mind if we passed a <span style="font-family: Courier New;">Recipient</span> instead of a <span style="font-family: Courier New;">Contact</span> as an <span style="font-family: Courier New;"><span style="text-decoration: underline;">in</span></span> parameter so why can&#8217;t we do it here? Because <span style="font-family: Courier New;">ref</span> parameters, like <span style="font-family: Courier New;">out</span> parameters, have a stricter requirement: you cannot assume the returned type is a more derived type than the parameter&#8217;s given type. To do so would not be type safe. The parameter in question <span style="text-decoration: underline;">must</span> be a <span style="font-family: Courier New;">ref Contact</span>.</p>
<h3>But This Works in Other Languages</h3>
<p>This <span style="text-decoration: underline;">may</span> sometimes work in languages that allow you to subvert type safety (most famously C and C++). It <span style="text-decoration: underline;">will</span> only work so long as you are lucky about your class layouts or your assumptions remain true. When either class layouts or your assumptions change your code will no longer work.</p>
<p>Here&#8217;s an example in C++. I run it in the debugger and it crashes on line 20 due to the type coercion done on line 41. This should not come as a surprise.</p>
<div style="font-size: 10pt; background: white; color: black; font-family: courier new;">
<p style="margin: 0px;"><span style="color: #2b91af;">    1</span> <span style="color: blue;">#include</span> <span style="color: #a31515;">&lt;string&gt;</span></p>
<p style="margin: 0px;"><span style="color: #2b91af;">    2</span> <span style="color: blue;">using</span> std::string;</p>
<p style="margin: 0px;"><span style="color: #2b91af;">    3</span> </p>
<p style="margin: 0px;"><span style="color: #2b91af;">    4</span> <span style="color: blue;">class</span> Contact</p>
<p style="margin: 0px;"><span style="color: #2b91af;">    5</span> {</p>
<p style="margin: 0px;"><span style="color: #2b91af;">    6</span> <span style="color: blue;">public</span>:</p>
<p style="margin: 0px;"><span style="color: #2b91af;">    7</span>     <span style="color: blue;">virtual</span> ~Contact() { }</p>
<p style="margin: 0px;"><span style="color: #2b91af;">    8</span> };</p>
<p style="margin: 0px;"><span style="color: #2b91af;">    9</span> </p>
<p style="margin: 0px;"><span style="color: #2b91af;">   10</span> <span style="color: blue;">class</span> Recipient : <span style="color: blue;">public</span> Contact</p>
<p style="margin: 0px;"><span style="color: #2b91af;">   11</span> {</p>
<p style="margin: 0px;"><span style="color: #2b91af;">   12</span> <span style="color: blue;">public</span>:</p>
<p style="margin: 0px;"><span style="color: #2b91af;">   13</span>     Recipient()</p>
<p style="margin: 0px;"><span style="color: #2b91af;">   14</span>         : m_favoriteColor(<span style="color: #a31515;">&#8220;Alice Blue&#8221;</span>)</p>
<p style="margin: 0px;"><span style="color: #2b91af;">   15</span>     {</p>
<p style="margin: 0px;"><span style="color: #2b91af;">   16</span>     }</p>
<p style="margin: 0px;"><span style="color: #2b91af;">   17</span> </p>
<p style="margin: 0px;"><span style="color: #2b91af;">   18</span>     string GetFavoriteColor() <span style="color: blue;">const</span></p>
<p style="margin: 0px;"><span style="color: #2b91af;">   19</span>     {</p>
<p style="margin: 0px;"><span style="color: #2b91af;">   20</span>         <span style="color: blue;">return</span> m_favoriteColor;</p>
<p style="margin: 0px;"><span style="color: #2b91af;">   21</span>     }</p>
<p style="margin: 0px;"><span style="color: #2b91af;">   22</span> </p>
<p style="margin: 0px;"><span style="color: #2b91af;">   23</span> <span style="color: blue;">private</span>:</p>
<p style="margin: 0px;"><span style="color: #2b91af;">   24</span>     <span style="color: blue;">int</span> m_otherStuff[256];</p>
<p style="margin: 0px;"><span style="color: #2b91af;">   25</span>     string m_favoriteColor;</p>
<p style="margin: 0px;"><span style="color: #2b91af;">   26</span> };</p>
<p style="margin: 0px;"><span style="color: #2b91af;">   27</span> </p>
<p style="margin: 0px;"><span style="color: #2b91af;">   28</span> <span style="color: blue;">class</span> Sender : <span style="color: blue;">public</span> Contact</p>
<p style="margin: 0px;"><span style="color: #2b91af;">   29</span> {</p>
<p style="margin: 0px;"><span style="color: #2b91af;">   30</span> };</p>
<p style="margin: 0px;"><span style="color: #2b91af;">   31</span> </p>
<p style="margin: 0px;"><span style="color: #2b91af;">   32</span> <span style="color: blue;">void</span> FetchContact(<span style="color: blue;">unsigned</span> row, Contact** ppContact)</p>
<p style="margin: 0px;"><span style="color: #2b91af;">   33</span> {</p>
<p style="margin: 0px;"><span style="color: #2b91af;">   34</span>     *ppContact = <span style="color: blue;">new</span> Sender();</p>
<p style="margin: 0px;"><span style="color: #2b91af;">   35</span> }</p>
<p style="margin: 0px;"><span style="color: #2b91af;">   36</span> </p>
<p style="margin: 0px;"><span style="color: #2b91af;">   37</span> <span style="color: blue;">int</span> _tmain(<span style="color: blue;">int</span> argc, _TCHAR* argv[])</p>
<p style="margin: 0px;"><span style="color: #2b91af;">   38</span> {</p>
<p style="margin: 0px;"><span style="color: #2b91af;">   39</span>     Recipient* pRecipient;</p>
<p style="margin: 0px;"><span style="color: #2b91af;">   40</span> </p>
<p style="margin: 0px;"><span style="color: #2b91af;">   41</span>     FetchContact(0, (Contact**)&amp;pRecipient);</p>
<p style="margin: 0px;"><span style="color: #2b91af;">   42</span> </p>
<p style="margin: 0px;"><span style="color: #2b91af;">   43</span>     string fave = pRecipient-&gt;GetFavoriteColor();</p>
<p style="margin: 0px;"><span style="color: #2b91af;">   44</span> </p>
<p style="margin: 0px;"><span style="color: #2b91af;">   45</span>     <span style="color: blue;">delete</span> pRecipient;</p>
<p style="margin: 0px;"><span style="color: #2b91af;">   46</span> </p>
<p style="margin: 0px;"><span style="color: #2b91af;">   47</span>     <span style="color: blue;">return</span> 0;</p>
<p style="margin: 0px;"><span style="color: #2b91af;">   48</span> }</p>
</div>
<p> Hope that helps.</p>
<div class="blogger-post-footer"><img src="https://blogger.googleusercontent.com/tracker/19212077-3384792629010575968?l=www.codeneverwritten.com" alt="" width="1" height="1" /></div>
]]></content:encoded>
			<wfw:commentRss>http://projectcoho.com/?feed=rss2&#038;p=12</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Say (code) what you mean</title>
		<link>http://projectcoho.com/?p=13</link>
		<comments>http://projectcoho.com/?p=13#comments</comments>
		<pubDate>Thu, 01 Feb 2007 16:26:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Code Review]]></category>

		<guid isPermaLink="false">http://projectcoho.com/?p=13</guid>
		<description><![CDATA[A bright, shiny object caught my eye few weeks ago while I was hiking in the snowy Cascades. Upon investigation I found a saucer shaped craft glistening in the sun. It appeared to be a space travel-capable sort of vehicle with a &#8230; <a href="http://projectcoho.com/?p=13">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>A bright, shiny object caught my eye few weeks ago while I was hiking in the snowy Cascades. Upon investigation I found a saucer shaped craft glistening in the sun. It appeared to be a space travel-capable sort of vehicle with a translucent bubble-shaped canopy that had sprung open, apparently on impact with this planet. I peered into the craft and saw a gray-green being with a large head and eyes. This being appeared to be well-frozen and so, concluding that continuing my investigation would not disturb this being, I continued to poke around the strange craft a bit more.</p>
<p>In what I would describe as a cockpit I found a something like a display panel which was flashing this message:</p>
<blockquote><p><span style="font-family: Courier New; color: #0000a0; font-size: x-small;">Exception in thread &#8220;nav&#8221; java.lang.ClassCastException: java.lang.Double<br />
at NavigationWaypoint.&lt;init&gt;(NavigationWaypoint.java:10)<br />
at FindWaypoint.FindNextWaypoint(FindWaypoint.java:94)<br />
&#8230;</span></p></blockquote>
<p>Obviously this sparked my curiosity! In looking around the cockpit I discovered a bit of paper&#8211;more like mylar, really&#8211;clutched in what for now I&#8217;ll call the unfortunate being&#8217;s hand. I liberated this piece of paper and found printing on it. I was shocked to see what the paper showed:</p>
<div style="font-size: 10pt; background: white; color: black; font-family: courier new;">
<p style="margin: 0px;"><span style="color: #2b91af;">    7</span> <span style="color: blue;">class</span> NavigationWaypoint</p>
<p style="margin: 0px;"><span style="color: #2b91af;">    8</span> {</p>
<p style="margin: 0px;"><span style="color: #2b91af;">    9</span>     <span style="color: blue;">public</span> NavigationWaypoint(<span style="color: #2b91af;">Object</span> name) {</p>
<p style="margin: 0px;"><span style="color: #2b91af;">   10</span>         <span style="color: blue;">this</span>.name = (<span style="color: #2b91af;">String</span>)name;</p>
<p style="margin: 0px;"><span style="color: #2b91af;">   11</span>     }</p>
<p style="margin: 0px;"><span style="color: #2b91af;">   12</span> </p>
<p style="margin: 0px;"><span style="color: #2b91af;">   13</span>     <span style="color: blue;">public</span> <span style="color: #2b91af;">String</span> getName() {</p>
<p style="margin: 0px;"><span style="color: #2b91af;">   14</span>         <span style="color: blue;">return</span> name;</p>
<p style="margin: 0px;"><span style="color: #2b91af;">   15</span>     }</p>
<p style="margin: 0px;"><span style="color: #2b91af;">   16</span> </p>
<p style="margin: 0px;"><span style="color: #2b91af;">   </span>&#8230;</p>
<p style="margin: 0px;"><span style="color: #2b91af;">   32</span>     <span style="color: blue;">private</span> <span style="color: #2b91af;">String</span> name;</p>
<p style="margin: 0px;"><span style="color: #2b91af;">   33</span> }</p>
</div>
<p>What a tragedy! Clearly the author of this code (presumably an inexperienced alien programmer) had errantly designed the instance constructor to take an Object rather than a String. In doing so the coder then needed a typecast in order to coerce the Object to a String in order to set the <em>name</em> field.</p>
<p>I don&#8217;t know about most, but on <em>my</em> planet such use of a typecast is a pretty strong clue that the programmer should look around to see why the typecast is necessary; it may be indicative of a design error.</p>
<p>In fact, in this case it is a design error. The NavigationWaypoint class has a <em>name</em> field that contains a string, yet the constructor allows the caller to pass in an object of any type. This unfortunate error and the use of a typecast caused the error to manifest itself during execution of the code; obviously some other code passed in a Double rather than a String, probably a simple coding error. If the constructor had been coded to accept a String this coding error would have been caught at compile time rather than during execution, saving this little fellow the exasperation of debugging on the fly and waking up frozen on a strange planet. If only the constructor had been coded to correctly represent the type&#8217;s data&#8230;.</p>
<p>(This post was inspired by a true story that had nothing to do with navigation.)</p>
<div id="0767317B-992E-4b12-91E0-4F059A8CECA8:a96d05ed-fed7-4f63-8e1f-73b5c1fb05ed" class="wlWriterSmartContent" style="display: inline; float: none; margin: 0px; padding: 0px;">Technorati tags: <a rel="tag" href="http://technorati.com/tags/Coding">Coding</a>, <a rel="tag" href="http://technorati.com/tags/Design">Design</a>, <a rel="tag" href="http://technorati.com/tags/Development">Development</a>, <a rel="tag" href="http://technorati.com/tags/Software">Software</a></div>
<div class="blogger-post-footer"><img src="https://blogger.googleusercontent.com/tracker/19212077-535893304355639581?l=www.codeneverwritten.com" alt="" width="1" height="1" /></div>
]]></content:encoded>
			<wfw:commentRss>http://projectcoho.com/?feed=rss2&#038;p=13</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>C# Anonymous Delegates: Your Stack or Mine?</title>
		<link>http://projectcoho.com/?p=14</link>
		<comments>http://projectcoho.com/?p=14#comments</comments>
		<pubDate>Fri, 27 Oct 2006 05:46:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Coding]]></category>

		<guid isPermaLink="false">http://projectcoho.com/?p=14</guid>
		<description><![CDATA[I want to take a moment to call out what I think is an interesting part of my previous post. Anonymous delegates have an interesting capability. To illustrate, here&#8217;s an example: using System; using System.Threading; class Program { static void &#8230; <a href="http://projectcoho.com/?p=14">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I want to take a moment to call out what I think is an interesting part of <a href="http://www.codeneverwritten.com/2006/10/ctrl-c-and-net-console-application.html">my previous post</a>. Anonymous delegates have an interesting capability. To illustrate, here&#8217;s an example:</p>
<pre><span style="color: #004080;">using System;
using System.Threading;

class Program
{
    static void Main(string[] args)
    {
        // 'num' lives on the main thread's stack.
        int num = 0;
        Console.WriteLine("initial num=" + num);

        Thread thread = new Thread(
            delegate()
            {
                // Yet this delegate running on a different thread with
                // it's own stack has access to 'num' as well.
                num = 42;
            });

        thread.Start(); // Start the worker thread.
        thread.Join();  // Wait until the worker thread has finished.

        Console.WriteLine("final num=" + num);
    }
}</span></pre>
<p> </p>
<p>It&#8217;s pretty simple. This program declares and initializes a variable named <span style="font-family: Courier New; color: #004080;"><strong>num</strong></span>, creates and starts a thread that will set <span style="font-family: Courier New; color: #004080;"><strong>num</strong></span> to a different value, then waits for the thread to to complete. In the program&#8217;s output we see that <span style="font-family: Courier New; color: #004080;"><strong>num</strong></span> has indeed been set to 42. Here&#8217;s the view from the command line:</p>
<pre><span style="color: #008000;">F:tmp&gt;csc Program.csMicrosoft (R) Visual C# 2005 Compiler version 8.00.50727.42for Microsoft (R) Windows (R) 2005 Framework version 2.0.50727Copyright (C) Microsoft Corporation 2001-2005. All rights reserved.

F:tmp&gt;Program.exeinitial num=0final num=42</span></pre>
<p> </p>
<p>Okay, that&#8217;s as expected. But wait&#8211;<span style="font-family: Courier New; color: #004080;"><strong>num</strong></span> lives on the main thread&#8217;s stack. How is it that the second thread we&#8217;ve created has access to <span style="font-family: Courier New; color: #004080;"><strong>num</strong></span>? <span style="font-family: Courier New; color: #004080;"><strong>num</strong></span> isn&#8217;t on the second thread&#8217;s stack and it would be a pretty scary thing if the second thread had direct access to the first thread&#8217;s stack. All sorts of mayhem could ensue. Providing access to another thread&#8217;s stack isn&#8217;t exactly the sort of thing we want to happen in managed code.</p>
<h3>Chicanery?</h3>
<p>As it turns out, though it <em>appears</em> that <span style="font-family: Courier New; color: #004080;"><strong>num</strong></span> is a stack variable in the main method <em>it is not</em>. What we&#8217;re experiencing here is a convenience provided by the compiler. Or rather, a trick. A sleight-of-hand. An illusion. <span style="font-family: Courier New; color: #004080;"><strong>num</strong></span> doesn&#8217;t actually live on the stack.</p>
<p>In fact, the compiler has made <span style="font-family: Courier New; color: #004080;"><strong>num</strong></span> a field in a compiler generated class so that it can be made available <em>on the heap</em> to the delegate. Here&#8217;s the compiled code, courtesy of <a href="http://www.aisto.com/roeder/dotnet/">.NET Reflector</a>:</p>
<pre><span style="color: #408080;">[CompilerGenerated]
private sealed class &lt;&gt;c__DisplayClass1
{
      // Methods
      public &lt;&gt;c__DisplayClass1() { }
      public void &lt;main&gt;b__0()
      {
          this.num = 0x2a;
      }</span></pre>
<pre><span style="color: #408080;">      // Fields
      public int num;
}</span></pre>
<p> </p>
<p>The compiler has given our anonymous delegate method a name: it&#8217;s <span style="font-family: Courier New; color: #408080;">&lt;main&gt;b__0()</span> on this compiler generated class. As a member of this class it obviously has access to <span style="font-family: Courier New; color: #004080;"><strong>num</strong></span>. The illusion is completed by fitting out the Main method so that it has an instance of <span style="font-family: Courier New; color: #408080;">&lt;&gt;c__DisplayClass1</span> to use:</p>
<pre><span style="color: #408080;">private static void Main(string[] args)
{
      Program.&lt;&gt;c__DisplayClass1 class1 = new Program.&lt;&gt;c__DisplayClass1();
      class1.num = 0;
      Console.WriteLine("initial num=" + class1.num);</span></pre>
<pre><span style="color: #408080;">      Thread thread1 = new Thread(new ThreadStart(class1.b__0));
      thread1.Start();
      thread1.Join();

</span><span style="color: #408080;">      Console.WriteLine("final num=" + class1.num);
}</span></pre>
<p> </p>
<p>So now our <span style="font-family: Courier New; color: #408080;">Main</span> method has an instance of an object on the heap and can set <span style="font-family: Courier New; color: #004080;"><strong>num</strong></span> to zero since <span style="font-family: Courier New; color: #004080;"><strong>num</strong></span> is a public field on the compiler generated class.</p>
<p>And so, both threads are accessing a variable&#8211;not on the stack, but on the heap and accessible to both threads. This helpful behind-the-scenes work by the C# compiler allows us to keep the simplicity of the original code in this example; otherwise, we&#8217;d need to implement something like what the compiler has done for us. </p>
<div id="0767317B-992E-4b12-91E0-4F059A8CECA8:5f17122d-4172-44ad-bad3-b04665f80be7" class="wlWriterSmartContent" style="display: inline; margin: 0px; padding: 0px;">Technorati tags: <a rel="tag" href="http://technorati.com/tags/.Net">.Net</a>, <a rel="tag" href="http://technorati.com/tags/C#">C#</a>, <a rel="tag" href="http://technorati.com/tags/Coding">Coding</a></div>
<p>[Edit: Fix up formatting.]</p>
<div class="blogger-post-footer"><img src="https://blogger.googleusercontent.com/tracker/19212077-116192799011487821?l=www.codeneverwritten.com" alt="" width="1" height="1" /></div>
]]></content:encoded>
			<wfw:commentRss>http://projectcoho.com/?feed=rss2&#038;p=14</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Ctrl-C and the .NET console application</title>
		<link>http://projectcoho.com/?p=15</link>
		<comments>http://projectcoho.com/?p=15#comments</comments>
		<pubDate>Thu, 19 Oct 2006 06:39:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Coding]]></category>

		<guid isPermaLink="false">http://projectcoho.com/?p=15</guid>
		<description><![CDATA[I occasionally find myself writing a .NET console application, usually a one-off program used to test code that I&#8217;m working on. C# seems well-disposed to writing such programs. For example, I might need an application to listen for messages from &#8230; <a href="http://projectcoho.com/?p=15">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I occasionally find myself writing a .NET console application, usually a one-off program used to test code that I&#8217;m working on. C# seems well-disposed to writing such programs. For example, I might need an application to listen for messages from another application, whether over sockets, HTTP, or another protocol&#8211;the sort of application that would listen for and process incoming messages, continuing forever. It&#8217;s the sort of app you simply run from a console window and when you&#8217;re done give it the old Ctrl-C. Just hit Ctrl-C or Ctrl-Break on the console window and the application quickly goes away.  </p>
<p>Now, there&#8217;s actually something a little sinister going on here&#8230; when the app goes away it&#8217;s actually exits rather abruptly. There’s no exception thrown, no catch or finally blocks executed&#8211;it just (poof) goes away. This isn’t often a problem for me, but if my program modifies some system state while it’s running and needs to revert that state on exit, well, then it is an issue.  </p>
<p>As a simple example consider a program that logs incoming messages. It may have a file open and log messages as they come in. (Or it could alter a registry setting or some other system state to indicate its presence only to revert that setting on exit. Get the idea?) If the app doesn’t terminate normally, how can it clean up after itself?  </p>
<h3>First Try: Simple, but broken</h3>
<p>To make this a bit more concrete consider this example code. The tricky bit is that when you press Ctrl-C to terminate the program there is no clean up being done. Specifically, the log file isn&#8217;t flushed to disk. When I run this program and hit Ctrl-C the log file is left entirely empty. This is because the program hasn&#8217;t written enough to the file to flush the file buffer to disk when the program is interrupted. Remember, this program isn&#8217;t exiting normally when we use Ctrl-C to interrupt it. In this case, the text <span style="font-family: Lucida Console;">&#8220;Handling messages.&#8221;</span> never appears in the log.  </p>
<pre><span style="color: #004080;">using System;
using System.IO;
using System.Threading;

namespace Example
{
   class Program
   {
       static void Main(string[] args)
       {
           try
           {
               using (FileStream fs = new FileStream("sample.log", FileMode.Append, FileAccess.Write, FileShare.None))
               using (StreamWriter logWriter = new StreamWriter(fs))
               {
                   Console.WriteLine(
                       "This is the basic program. It doesn't call the clean-up code if you use Ctrl-C, "
                       + "and the log file isn't flushed to disk.");
                   ProcessIncomingMessages(logWriter);
               }
           }
           finally
           {
               Console.WriteLine("Clean-up code invoked.");
           }
       }

       static void ProcessIncomingMessages(TextWriter writer)
       {
           writer.WriteLine("Handling messages.");
           Thread.Sleep(Timeout.Infinite); // Well, pretend it processes messages, okay?
       }
   }
}</span></pre>
<p>   </p>
<h3>Console.CancelKeyPress Event</h3>
<p>As you might guess there is a way to handle Ctrl-C and Ctrl-Break and it&#8217;s the <span style="font-family: Lucida Console;">Console</span>&#8216;s <span style="font-family: Lucida Console;"><a href="http://msdn2.microsoft.com/en-us/library/system.console.cancelkeypress.aspx" target="_blank">CancelKeyPress</a></span> event. By providing a delegate you can have the runtime notify you when a &#8220;cancel key&#8221; has been pressed. Here I&#8217;ve  </p>
<ul>
<li>Added an <em><a href="http://msdn2.microsoft.com/en-us/library/0yw3tz5k.aspx">anonymous delegate</a></em> to clean up if Ctrl-C or Ctrl-Break is pressed. As you can see it flushes the writer and closes the file stream.</li>
<li>I&#8217;ve also moved the fs and logWriter variables outside their using statements to allow access from the finally block.</li>
</ul>
<p>If you read this code from top-to-bottom it may appear unusual that the code in the CancelKeyPress delegate appears to be using logWriter and fs before either variable is assigned a non-null reference. In fact, what is really happening there is that we&#8217;re declaring the code for the delegate <em>in line</em> and handing it off to the CancelKeyPress event&#8211;it isn&#8217;t executed where its position in the source suggests. In this case it&#8217;s only executed when Ctrl-C or Ctrl-Break is pressed.  </p>
<pre><span style="color: #004080;">        static void Main(string[] args)
       {
           FileStream fs = null;
           StreamWriter logWriter = null;
           try
           {
               Console.WriteLine("This shows use of the cancel handler.");
               Console.CancelKeyPress += delegate
               {
                   Console.WriteLine("Clean-up code invoked in CancelKeyPress handler.");
                   if (logWriter != null)
                       logWriter.Flush();
                   if (fs != null)
                       fs.Close();
                   // The application terminates directly after executing this delegate.
               };

               fs = new FileStream("sample.log", FileMode.Append, FileAccess.Write, FileShare.None);
               logWriter = new StreamWriter(fs);
               ProcessIncomingMessages(logWriter);
           }
           finally
           {
               Console.WriteLine("Clean-up code invoked in finally.");
               if (logWriter != null)
                   logWriter.Flush();
               if (fs != null)
                   fs.Close();
           }
       }</span></pre>
<h3>Consolidating Clean Up Code</h3>
<p>Here I&#8217;ve opted to put the clean-up code in one place rather than duplicating it in the finally block. I&#8217;ve declared my own delegate type CleanUpMethod so I have a tidy, parameter-less delegate that I can also call from the finally block.  </p>
<pre><span style="color: #004080;">       delegate void CleanUpMethod();

       static void Main(string[] args)
       {
           FileStream fs = null;
           StreamWriter logWriter = null;

           string cleanUpLocation = "handler.";
           CleanUpMethod cleanUp =
               delegate
               {
                   Console.WriteLine("Clean-up code invoked in " + cleanUpLocation);
                   if (logWriter != null)
                       logWriter.Flush();
                   if (fs != null)
                       fs.Close();
               };

           try
           {
               Console.WriteLine("This shows use of a single, no-param clean-up handler.");
               Console.CancelKeyPress +=
                   delegate
                   {
                       cleanUp();
                       // The application terminates directly after executing this delegate.
                   };

               fs = new FileStream("sample.log", FileMode.Append, FileAccess.Write, FileShare.None);
               logWriter = new StreamWriter(fs);
               ProcessIncomingMessages(logWriter);
           }
           finally
           {
               cleanUpLocation = "finally.";
               cleanUp();
           }
       }</span></pre>
<p>But why put the clean-up code in a delegate instead of it&#8217;s own method? One very helpful aspect of using an anonymous delegate in this example is that the delegate code has access to the local variables in this method. If you use <a href="http://www.aisto.com/roeder/dotnet/">Lutz Roeder&#8217;s .NET Reflector</a> to take a look at this program you will see the substantial amount of work that the compiler does for you under the covers in order to provide easy access to the local variables from the delegate method:  </p>
<pre><span style="color: #408080;">private static void Main(string[] args)
{
     ConsoleCancelEventHandler handler1 = null;
     Program.&lt;&gt;c__DisplayClass3 class1 = new Program.&lt;&gt;c__DisplayClass3();
     class1.fs = null;
     class1.logWriter = null;
     class1.cleanUpLocation = "handler.";
     class1.cleanUp = new Program.CleanUpMethod(class1.b__0);
     try
     {
           Console.WriteLine("This shows use of a single, no-param clean-up handler.");
           if (handler1 == null)
           {
                 handler1 = new ConsoleCancelEventHandler(class1.b__1);
           }</span></pre>
<pre><span style="color: #408080;">           Console.CancelKeyPress += handler1;
           class1.fs = new FileStream("sample.log", FileMode.Append, FileAccess.Write, FileShare.None);
           class1.logWriter = new StreamWriter(class1.fs);
           Program.ProcessIncomingMessages(class1.logWriter);
     }
     finally
     {
           class1.cleanUpLocation = "finally.";
           class1.cleanUp();
     }
}</span></pre>
<pre>I'm pleased the C# compiler does so much work just to make my life easier. <img src='http://projectcoho.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </pre>
<pre>
<div id="0767317B-992E-4b12-91E0-4F059A8CECA8:cdb641a5-f8f4-4b54-97fb-36a6cf4039c4" class="wlWriterSmartContent" style="margin: 0px; padding: 0px; display: inline;">Technorati tags: <a rel="tag" href="http://technorati.com/tags/.Net">.Net</a>, <a rel="tag" href="http://technorati.com/tags/C#">C#</a>, <a rel="tag" href="http://technorati.com/tags/Coding">Coding</a></div>
</pre>
]]></content:encoded>
			<wfw:commentRss>http://projectcoho.com/?feed=rss2&#038;p=15</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
