<?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</title>
	<atom:link href="http://projectcoho.com/?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>File. Close. No!</title>
		<link>http://projectcoho.com/?p=9</link>
		<comments>http://projectcoho.com/?p=9#comments</comments>
		<pubDate>Thu, 29 Nov 2007 04:03:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Fun]]></category>
		<category><![CDATA[Security]]></category>

		<guid isPermaLink="false">http://projectcoho.com/?p=9</guid>
		<description><![CDATA[I enjoyed listening to Scott Hanselman&#8217;s podcast interview of Larry Osterman today. Larry has been working at Microsoft for more than 23 years now and usually has words of interest to software developers on his blog. As the discussion turned &#8230; <a href="http://projectcoho.com/?p=9">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I enjoyed listening to Scott Hanselman&#8217;s podcast <a href="http://www.hanselminutes.com/default.aspx?showID=107" target="_blank">interview of Larry Osterman</a> today. Larry has been working at Microsoft for more than 23 years now and usually has words of interest to software developers <a href="http://blogs.msdn.com/larryosterman/" target="_blank">on his blog</a>.</p>
<p>As the discussion turned to security issues I was reminded of a security issue I pointed out to a colleague back in, well, I believe it was the first half of the 90&#8242;s. The issue: the attack vector brought about by speaker-independent voice recognition. The scenario: the disgruntled office worker running through the cubicle farm, shouting &#8220;File. Close. No! File. Close. No!&#8221;</p>
<p>It amuses me to think that perhaps the new ribbon-and-pearl command structure of Office 2007 apps has gone a long way in negating that issue. <img src='http://projectcoho.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<div id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:2d74803d-abce-427d-8dda-877b05b4be99" class="wlWriterSmartContent" style="display: inline; margin: 0px; padding: 0px;">Technorati tags: <a rel="tag" href="http://technorati.com/tags/Security">Security</a></div>
<div class="blogger-post-footer"><img src="https://blogger.googleusercontent.com/tracker/19212077-8715026386461774143?l=www.codeneverwritten.com" alt="" width="1" height="1" /></div>
]]></content:encoded>
			<wfw:commentRss>http://projectcoho.com/?feed=rss2&#038;p=9</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Whither Orcas?</title>
		<link>http://projectcoho.com/?p=10</link>
		<comments>http://projectcoho.com/?p=10#comments</comments>
		<pubDate>Sat, 23 Jun 2007 03:09:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Tools]]></category>

		<guid isPermaLink="false">http://projectcoho.com/?p=10</guid>
		<description><![CDATA[I&#8217;ve been perusing An Overview of Microsoft Visual Studio Code Name &#8220;Orcas&#8221; White Paper with a curiosity known only to those who are curious about what will ship in the Visual Studio &#8220;Orcas&#8221; release. I am intrigued. In the three areas &#8230; <a href="http://projectcoho.com/?p=10">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been perusing <a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=17319EB4-299C-43B8-A360-A1C2BD6A421B&amp;displaylang=en" target="_blank">An Overview of Microsoft Visual Studio Code Name &#8220;Orcas&#8221; White Paper</a> with a curiosity known only to those who are curious about what will ship in the Visual Studio &#8220;Orcas&#8221; release. <img src='http://projectcoho.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  I am intrigued. In the three areas in which Orcas purports to deliver key advances, I&#8217;m most intrigued with the third:</p>
<ul>
<li>Improve Developer Productivity</li>
<li>Manage the Application Life Cycle</li>
<li>Employ the Latest Technologies</li>
</ul>
<p>After all, true geeks are more interested in the latest technologies than in process, right? <img src='http://projectcoho.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  Of interest to me in the Orcas release of Visual Studio, I see:</p>
<p><strong>LINQ</strong> (pp. 8,13)</p>
<p>I admit I&#8217;m a bit of a Luddite when it comes to language features. It took me a while to see that C#&#8217;s &#8220;using&#8221; syntax was clearly a good thing. What do you expect from a C++ developer whose first C++ compiler was a <em><a href="http://en.wikipedia.org/wiki/Cfront" target="_blank">cfront</a></em> translator&#8211;we didn&#8217;t have C++ compilers back then. Don&#8217;t give me syntactic sugar&#8211;let me do it the hard way! Give me a preprocessor!</p>
<p>All the same, LINQ seems to be a boon to anyone who wants to query over structured data. I&#8217;ll likely adopt it in (personal) record time.</p>
<p><strong>Further support for building WPF applications</strong> (pp. 5, 19)</p>
<p>Debugging support for WPF. I have to wonder what that will look like. Will I be able to step through XAML?</p>
<p><strong>New APIs in Window Vista</strong> (p. 6)</p>
<p>Seriously, are there really &#8220;more than 8,000 new native APIs available in Windows Vista?&#8221; My brain hurts. Maybe I need to buy a llama farm and learn to live the simple life. I mean, I started programming Windows code in 1991. That&#8217;s later than many, earlier than most. Dear God, I even digested <a href="http://msdn.microsoft.com/archive/default.asp?url=/archive/en-us/dnarolegen/html/msdn_aboutole.asp" target="_blank">Kraig Brockschmidt&#8217;s book, Inside OLE2</a>! Gah! Is my brain going to fill up and return E_OUTOFMEMORY? And will that be a fatal error?! <img src='http://projectcoho.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><strong>New managed add-in model</strong> (pp. 14, 16)</p>
<p>I&#8217;ve seen some tough questions asked about how to control the impact of rogue add-ins in a managed application. The <a href="http://blogs.msdn.com/clraddins/default.aspx">CLR Add-In Team Blog</a> indicates someone at Microsoft is working at <a href="http://blogs.msdn.com/clraddins/archive/2007/01/12/welcome-to-the-clr-add-in-team-blog.aspx" target="_blank">addressing these issues</a>, as does this white paper.</p>
<p><strong>Lightweight reader/writer lock with deadlock-free upgrade support</strong> (p. 14)</p>
<p>Hmm, a slimmed-down read-writer lock that doesn&#8217;t support recursion. This sounds a bit like what Jeffrey Richter describes in CLR via C# (second edition, pages 642-643). I can&#8217;t wait to compare Richter&#8217;s version in <a href="http://www.wintellect.com/" target="_blank">Wintellect&#8217;s</a> Power Threading library with what Reflector tells me about Orcas&#8217; System.Threading.ReaderWriterLockSlim. It should be an educational experience. <img src='http://projectcoho.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><strong>New IO types that expose almost all pipe functionality provided by Windows</strong> (p. 15)</p>
<p>It&#8217;s about time. <img src='http://projectcoho.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><strong>A trace listener for ETW</strong> (p. 16)</p>
<p>Woot! High-perf event tracing!</p>
<p><strong>Peer Networking Classes</strong> (p. 17)</p>
<p>I don&#8217;t know how much of the <a href="http://msdn.microsoft.com/msdnmag/issues/06/10/PeerToPeer/" target="_blank">P2P</a> APIs this might encompass, but it&#8217;s definitely an area I&#8217;ll be experimenting with. I expect we&#8217;ll be seeing some very cool apps born out of this space. Apps we haven&#8217;t thought of yet.</p>
<p>Woof. As usual my eyes are bigger than my stomach. I hope to have time to explore at least a few of these areas. <img src='http://projectcoho.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<div id="0767317B-992E-4b12-91E0-4F059A8CECA8:46efead3-a2eb-4ab3-ae29-1c7fcd0210e9" class="wlWriterSmartContent" style="display: inline; margin: 0px; padding: 0px;">Technorati tags: <a rel="tag" href="http://technorati.com/tags/LINQ">LINQ</a>, <a rel="tag" href="http://technorati.com/tags/WPF">WPF</a>, <a rel="tag" href="http://technorati.com/tags/Vista">Vista</a>, <a rel="tag" href="http://technorati.com/tags/ETW">ETW</a>, <a rel="tag" href="http://technorati.com/tags/Peer%20Networking">Peer Networking</a></div>
<div class="blogger-post-footer"><img src="https://blogger.googleusercontent.com/tracker/19212077-8663848232801910390?l=www.codeneverwritten.com" alt="" width="1" height="1" /></div>
]]></content:encoded>
			<wfw:commentRss>http://projectcoho.com/?feed=rss2&#038;p=10</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Moving On&#8230;</title>
		<link>http://projectcoho.com/?p=11</link>
		<comments>http://projectcoho.com/?p=11#comments</comments>
		<pubDate>Sat, 23 Jun 2007 00:58:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Contracting]]></category>
		<category><![CDATA[Seattle]]></category>

		<guid isPermaLink="false">http://projectcoho.com/?p=11</guid>
		<description><![CDATA[It&#8217;s that time again, when one contract ends and another begins. I&#8217;m never able to wrap up all the loose ends that I&#8217;d like to. Yet it&#8217;s a bit renewing, helping one project through RTM and SP1, then picking up &#8230; <a href="http://projectcoho.com/?p=11">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s that time again, when one contract ends and another begins. I&#8217;m never able to wrap up all the loose ends that I&#8217;d like to.</p>
<p>Yet it&#8217;s a bit renewing, helping one project through RTM and SP1, then picking up and beginning fresh on something totally different with a completely different set of people. It&#8217;s interesting how from one project to the next people vary so much. It&#8217;s like they&#8217;re wired differently. <img src='http://projectcoho.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Aside from the pleasure of meeting and working with new people, I also enjoyed this view from my desk in recent months. (Sorry about the cell phone picture quality.) Can you find the Space Needle?</p>
<p><a href="http://www.codeneverwritten.com/images/MovingOn_F772/fs_view.jpg"><img style="border-width: 0px;" src="http://www.codeneverwritten.com/images/MovingOn_F772/fs_view_thumb.jpg" border="0" alt="The view from my desk" width="320" height="240" /></a></p>
<p>If experience is any indication my desk at my next assignment will likely face a beige wall in building 41 instead of downtown Seattle. But it involves some pretty cool software. Oh, well, you take the good with the bad. <img src='http://projectcoho.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<div id="0767317B-992E-4b12-91E0-4F059A8CECA8:55b675e8-0c24-4aba-b998-de6e22be35b2" class="wlWriterSmartContent" style="display: inline; margin: 0px; padding: 0px;">Technorati tags: <a rel="tag" href="http://technorati.com/tags/Contracting">Contracting</a>, <a rel="tag" href="http://technorati.com/tags/Seattle">Seattle</a></div>
<div class="blogger-post-footer"><img src="https://blogger.googleusercontent.com/tracker/19212077-7055554423600484637?l=www.codeneverwritten.com" alt="" width="1" height="1" /></div>
]]></content:encoded>
			<wfw:commentRss>http://projectcoho.com/?feed=rss2&#038;p=11</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>C#: Type issues with ref parameters</title>
		<link>http://projectcoho.com/?p=12</link>
		<comments>http://projectcoho.com/?p=12#comments</comments>
		<pubDate>Thu, 15 Feb 2007 22:09:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[C#]]></category>

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

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

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

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

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

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

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

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

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