<?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; Coding</title>
	<atom:link href="http://projectcoho.com/?cat=6&#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>Summer Series – Windows Phone 7 Development</title>
		<link>http://projectcoho.com/?p=58</link>
		<comments>http://projectcoho.com/?p=58#comments</comments>
		<pubDate>Mon, 09 Aug 2010 04:45:02 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[Mobile Development]]></category>
		<category><![CDATA[WP7]]></category>

		<guid isPermaLink="false">http://www.codeneverwritten.com/?p=58</guid>
		<description><![CDATA[This past week I attended a meeting of the Seattle Silverlight User Group. I&#8217;ve attended a number of these in the past and they have been reasonably interesting&#8211;largely a result, I think, of easy access to local Microsoft folks who &#8230; <a href="http://projectcoho.com/?p=58">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>This past week I attended a meeting of the <a href="http://seattlesilverlight.net/" target="_blank">Seattle Silverlight User Group</a>. I&#8217;ve attended a number of these in the past and they have been reasonably interesting&#8211;largely a result, I think, of easy access to local Microsoft folks who are happy to speak on Silverlight topics. Currently the group is running a series on Windows Phone 7 (WP7) development, the next meeting being the third installment in that series. I attended a WP7 Quickstart event in May and found that this presentation has certainly matured a bit since then, and with the subsequent Beta release there are additional topics to talk about.</p>
<p>What follows are some loose notes I took during the event; this isn&#8217;t intended to give you the experience of actually being there. The featured speakers were Pete Blois, a Program Manager on Expression Blend; and Jaime Rodriguez, a Technical Evangelist for Windows Phone.</p>
<p>Notable tidbits that came out during the presentations:</p>
<p>- Pete on the yet-to-appear Pivot and Panorama controls: &#8220;Those controls are coming.&#8221;<br />
- Jaime on future changes to the platform: &#8220;We&#8217;re not cutting a lot of things any more.&#8221;<br />
- The Bing Maps control will not require a paid license. (Jaime)</p>
<p>Pete Blois<br />
Pete demonstrated Expression Blend for Windows Phone 7. Blend for WP7 has improved quite a bit since the first release, most notable to me being the arrival of a full plate of Behaviors in the asset pane. Also new is the device tab with which you can change the theme (colors), device orientation (landscape and portrait), and whether you want to preview on the emulator or a device.</p>
<p>Pete did some quick demos of implementing page fly-out transitions and addressing orientation changes using Visual State Manager and Fluid Layout.</p>
<p>Blend also has new tooling in the properties pane for the ApplicationBar and its icons. (You&#8217;ll find that you can&#8217;t access this by selecting the ApplicationBar in the Objects and Timeline pane; you need to select the PhoneApplicationPage (the root element) and find ApplicationBar under Common Properties.) There you can adjust the colors, buttons, menu items and so on. Unfortunately we can&#8217;t use x:Name on ApplicationBar or bind to its properties; ApplicationBar is a wrapper over the native OS&#8217; app bar&#8211;you can&#8217;t bind because it&#8217;s not a Silverlight control owned by your app.</p>
<p>Performance of animations can be an issue, and Pete advises using storyboards as well as render and perspective transforms&#8211;these happen on the rendering thread (which is a high priority thread). Don&#8217;t animate on width, height or layout properties, as these cause invalidation of the layout.</p>
<p>Jaime Rodriguez<br />
Jaime discussed the core Silverlight controls: WP7 has those controls that make sense on the phone. Controls such as DataGrid make less sense in the mobile environment due to the lack of screen real estate. The Beta release is still missing some core controls, and tombstoning should see some improvement, but &#8220;We&#8217;re not cutting a lot of things any more.&#8221;</p>
<p>On the Panorama control (not in the Beta): Panorama should have 3 panels or more of content, otherwise it&#8217;s a bit silly to use it; more than 6 or 7 panels is a bit large and unwieldy. Panorama is good for exploring content, and imitates a continuous horizontal landscape that you can explore; it wraps around to the first panel if you swipe past the last one. Interestingly, Panorama does not have an app bar.</p>
<p>On the Pivot control (not in the Beta): it&#8217;s basically a slick tab control. Each page in the Pivot is related, but they don&#8217;t necessarily need to show the same content.</p>
<p>Bing maps control (not in the Beta): There will be a WP7-specific control for Bing maps. You will need to acquire and app ID to use this (as you do with Bing Maps in general) but you won&#8217;t have to pay for using the map. The map will be programmable, support gestures, and ship by RTM.</p>
<p>Jaime demonstrated UI navigation, especially the behavior of the back stack. I won&#8217;t get into this, as Yochay Kiriaty has a series on app activation/deactivation, tombstoning and the application execution model <a href="http://windowsteamblog.com/windows_phone/b/wpdev/archive/2010/07/15/understanding-the-windows-phone-application-execution-model-tombstoning-launcher-and-choosers-and-few-more-things-that-are-on-the-way-part-1.aspx" target="_blank">here</a>.</p>
<p>Summary<br />
All in all, it was a fairly informative two hours of information. I look forward to the <a href="http://seattlesilverlight.net/blogengine/post/2010/08/06/Summer-Series-Windows-Phone-7-Development-Taking-it-To-The-Next-Level-(Session-3).aspx" target="_blank">next event</a> on September 1st.</p>
]]></content:encoded>
			<wfw:commentRss>http://projectcoho.com/?feed=rss2&#038;p=58</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# 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>
		<item>
		<title>Red Flag</title>
		<link>http://projectcoho.com/?p=16</link>
		<comments>http://projectcoho.com/?p=16#comments</comments>
		<pubDate>Fri, 25 Aug 2006 06:15:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Code Review]]></category>
		<category><![CDATA[Coding]]></category>
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://projectcoho.com/?p=16</guid>
		<description><![CDATA[A red flag. It’s a warning. An alert. An indication of danger. A notification that something is amiss. There are red flags in the code we work on and the processes we follow. But do we see them? I missed &#8230; <a href="http://projectcoho.com/?p=16">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>A red flag. It’s a warning. An alert. An indication of danger. A notification that something is amiss. There are red flags in the code we work on and the processes we follow. But do we see them? I missed a red flag recently. It happened like this:</p>
<p>I had this curious bug I was trying to fix. The behavior suggested that it was most likely corrupted or uninitialized memory. That’s what intuition borne of experience was telling me, anyway. Randomly timed incorrect behavior in code that was processing a static stream of data. The input data was constant from one run to the next, the bits flowing through the code always the same, but the end result varied pretty much randomly in where and when it failed.</p>
<p>This suggested to me that we were processing someone else’s data or uninitialized data (which is really just someone else’s data from within the same process).</p>
<p>This body of C++ code was unfamiliar to me, so I found myself picking the brains of a coworker who had been around a while. In discussing the bug I found myself looking over his shoulder as he scrolled through some of the code in question, and he commented on a variable assignment that wasn’t used later in the function.</p>
<p>It was one of those <em>pfft</em> moments. “Been there, done that, seen it a million times.” A thoughtless assignment statement that someone typed in but then lost their train of thought. It looked something like this:</p>
<pre>void fn()
{
    size_t cbBase;
    void* pvData;

    if (get_value("base", &amp;cbBase, &amp;pvData))
    {
        store_data("base", cbBase, pvData);

        size_t cbExtended;
        void* pvDataExtended;

        if (get_value("extended", &amp;cbExtended, &amp;pvDataExtended))
        {
            store_data("extended", cbExtended, pvDataExtended);
            <span style="color: #000099;">cbBase = cbExtended;
</span>        }
    }
}</pre>
<p>And quickly we moved on to discuss what might really be wrong with the code. And that quickly I’d dismissed the red flag.</p>
<p>In a world where most of the code that I interact with is not my own, where dozens of changes wrought by numerous hands happen over a period of years can I really pass off a small, unexplained assignment like that above as an innocuous error? Any moderately complex code base will transmogrify over the years. Initial errors may indeed be simple coding issues that we wish would have been corrected by code review, but over time source code changes not randomly but with specific intent. And with any luck you have both bug reports and a source code revision system on which you can rely to find that intent.</p>
<p>The red flag, of course, was the meaningless assignment statement. More than a day later as I waded through diffs of check-ins from ages past I ran across the rationale for the assignment. In previous check-in an attempt was made to correct some bad behavior. A previous version of the code looked more like this:</p>
<pre>void fn()
{
    size_t cbBase;
    void* pvData;

    if (get_value("base", &amp;cbBase, &amp;pvData))
    {
        store_data("base", cbBase, pvData);

        size_t cbExtended;
        void* pvDataExtended;

        if (get_value("extended", &amp;cbExtended, &amp;pvDataExtended))
        {
            store_data("extended", cbExtended, pvDataExtended);
            <span style="color: #000099;">cbBase = cbExtended;
</span>        }

<span style="color: #000099;">        if (cbBase &lt; MINIMUM_EXPECTED_DATA_SIZE)
        {
            backfill_missing_extended_data();
        }
</span>    }
}</pre>
<p>Ah, the unexplained assignment was orphaned by a previous check-in. In an effort to correct a particular problem a developer had removed code but left behind an ineffective assignment. Interestingly&#8211;partly because I like a tidy ending&#8211;the bug the developer was fixing was strongly related to the bug I was pursuing. The original author’s intent for the assignment, it turns out, was probably not</p>
<pre>    cbBase = cbExtended;</pre>
<p>But</p>
<pre>    cbBase <span style="color: #000099;">+=</span> cbExtended;</pre>
<p>I reintroduced the missing code and patched up the assignment to find that, very conveniently, my bug was fixed as well. In the end, yes, it was incorrectly initialized data. It just wasn&#8217;t where I expected to look.</p>
<p>Funny thing, those red flags. They’re hard to see. Where have you seen them lately? (Or not?)</p>
<div class="blogger-post-footer"><img src="https://blogger.googleusercontent.com/tracker/19212077-115648652531095692?l=www.codeneverwritten.com" alt="" width="1" height="1" /></div>
]]></content:encoded>
			<wfw:commentRss>http://projectcoho.com/?feed=rss2&#038;p=16</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
