<?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>Quantum Bit Designs</title>
	<atom:link href="http://blog.quantumbitdesigns.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.quantumbitdesigns.com</link>
	<description>Multithreading, WPF, .NET and Software Designs</description>
	<lastBuildDate>Tue, 26 Jan 2010 15:17:04 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>MVVM &#8211; Lambda vs INotifyPropertyChanged vs DependencyObject</title>
		<link>http://blog.quantumbitdesigns.com/2010/01/26/mvvm-lambda-vs-inotifypropertychanged-vs-dependencyobject/</link>
		<comments>http://blog.quantumbitdesigns.com/2010/01/26/mvvm-lambda-vs-inotifypropertychanged-vs-dependencyobject/#comments</comments>
		<pubDate>Tue, 26 Jan 2010 05:38:04 +0000</pubDate>
		<dc:creator>Kevin</dc:creator>
				<category><![CDATA[Software Design]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[Binding]]></category>
		<category><![CDATA[MVVM]]></category>

		<guid isPermaLink="false">http://blog.quantumbitdesigns.com/?p=64</guid>
		<description><![CDATA[It has been about 1.5 years since I last posted. When the market crashed I became fascinated by world of trading (and software) and applied a bit of WPF knowledge to some research and software for another blog. I have 20+ topics still pending for this blog, so there is plenty to write about in 2010 and beyond.
I have been using [...]]]></description>
			<content:encoded><![CDATA[<p>It has been about 1.5 years since I last posted. When the market crashed I became fascinated by world of trading (and software) and applied a bit of WPF knowledge to some research and software for <a href="http://blog.quantumfading.com" target="_blank">another blog</a>. I have 20+ topics still pending for this blog, so there is plenty to write about in 2010 and beyond.</p>
<p>I have been using the MVVM pattern since the beginning of 2008. Since that time there have been plenty of complaints about INotifyPropertyChanged and how developers do not like using strings, etc. Last year several bloggers presented type-safe alternatives that used either reflection or lambda expressions. I really like the elegance and simplicity of the lambda expression, but many are quick to point out the poor performance (same for reflection). Unfortunately &#8216;poor performance&#8217; says little about usefulness of an implementation. The performance needs to be quantified and compared against all implementations so that &#8216;poor&#8217; can be put in perspective. Speed is not the only issue, as memory should be compared as well.</p>
<p>This article assumes the reader knows how to use INotifyPropertyChanged and DependencyObjects. (Note: the rest of this article will refer to the string implementation as INotifyPropertyChanged or just INotify). The lambda implementation that is used for the tests is as follows:</p>
<p><strong>INotifyPropertyChanged with Lambda</strong></p>
<div style="FONT-FAMILY: Lucida Console; BACKGROUND: white; COLOR: black; FONT-SIZE: 8pt">
<p style="MARGIN: 0px"><span style="COLOR: blue">public</span> <span style="COLOR: blue">static</span> <span style="COLOR: blue">class</span> <span style="COLOR: #2b91af">MvvmExtensions</span></p>
<p style="MARGIN: 0px">{</p>
<p style="MARGIN: 0px">    <span style="COLOR: blue">public</span> <span style="COLOR: blue">static</span> <span style="COLOR: blue">void</span> Raise(<span style="COLOR: blue">this</span> <span style="COLOR: #2b91af">PropertyChangedEventHandler</span> handler, <span style="COLOR: blue">object</span> sender, <span style="COLOR: #2b91af">Expression</span>&lt;<span style="COLOR: #2b91af">Func</span>&lt;<span style="COLOR: blue">object</span>&gt;&gt; expression)</p>
<p style="MARGIN: 0px">    {</p>
<p style="MARGIN: 0px">        <span style="COLOR: blue">if</span> (handler != <span style="COLOR: blue">null</span>)</p>
<p style="MARGIN: 0px">        {</p>
<p style="MARGIN: 0px">            <span style="COLOR: blue">if</span> (expression.NodeType != <span style="COLOR: #2b91af">ExpressionType</span>.Lambda)</p>
<p style="MARGIN: 0px">            {</p>
<p style="MARGIN: 0px">                <span style="COLOR: blue">throw</span> <span style="COLOR: blue">new</span> <span style="COLOR: #2b91af">ArgumentException</span>(<span style="COLOR: #a31515">&#8220;Value must be a lamda expression&#8221;</span>, <span style="COLOR: #a31515">&#8220;expression&#8221;</span>);</p>
<p style="MARGIN: 0px">            }</p>
<p style="MARGIN: 0px"> </p>
<p style="MARGIN: 0px">            <span style="COLOR: blue">var</span> body = expression.Body <span style="COLOR: blue">as</span> <span style="COLOR: #2b91af">MemberExpression</span>;</p>
<p style="MARGIN: 0px"> </p>
<p style="MARGIN: 0px">            <span style="COLOR: blue">if</span> (body == <span style="COLOR: blue">null</span>)</p>
<p style="MARGIN: 0px">            {</p>
<p style="MARGIN: 0px">                <span style="COLOR: blue">throw</span> <span style="COLOR: blue">new</span> <span style="COLOR: #2b91af">ArgumentException</span>(<span style="COLOR: #a31515">&#8220;&#8216;x&#8217; should be a member expression&#8221;</span>);</p>
<p style="MARGIN: 0px">            }</p>
<p style="MARGIN: 0px"> </p>
<p style="MARGIN: 0px">            <span style="COLOR: blue">string</span> propertyName = body.Member.Name;</p>
<p style="MARGIN: 0px">            handler(sender, <span style="COLOR: blue">new</span> <span style="COLOR: #2b91af">PropertyChangedEventArgs</span>(propertyName));</p>
<p style="MARGIN: 0px">        }</p>
<p style="MARGIN: 0px">    }</p>
<p style="MARGIN: 0px">}</p>
</div>
<p><!--EndFragment--></p>
<div style="FONT-FAMILY: Lucida Console; BACKGROUND: white; COLOR: black; FONT-SIZE: 8pt">
<p style="MARGIN: 0px"><span style="COLOR: blue">public</span> <span style="COLOR: blue">class</span> <span style="COLOR: #2b91af">DummyLambdaViewModel</span> : <span style="COLOR: #2b91af">INotifyPropertyChanged</span></p>
<p style="MARGIN: 0px">{</p>
<p style="MARGIN: 0px">    <span style="COLOR: blue">private</span> <span style="COLOR: blue">string</span> _dummyProperty;</p>
<p style="MARGIN: 0px"> </p>
<p style="MARGIN: 0px">    <span style="COLOR: blue">public</span> <span style="COLOR: blue">string</span> DummyProperty</p>
<p style="MARGIN: 0px">    {</p>
<p style="MARGIN: 0px">        <span style="COLOR: blue">get</span></p>
<p style="MARGIN: 0px">        {</p>
<p style="MARGIN: 0px">            <span style="COLOR: blue">return</span> <span style="COLOR: blue">this</span>._dummyProperty;</p>
<p style="MARGIN: 0px">        }</p>
<p style="MARGIN: 0px">        <span style="COLOR: blue">set</span></p>
<p style="MARGIN: 0px">        {</p>
<p style="MARGIN: 0px">            <span style="COLOR: blue">this</span>._dummyProperty = <span style="COLOR: blue">value</span>;</p>
<p style="MARGIN: 0px">            OnPropertyChanged(() =&gt; <span style="COLOR: blue">this</span>.DummyProperty);</p>
<p style="MARGIN: 0px">        }</p>
<p style="MARGIN: 0px">    }</p>
<p style="MARGIN: 0px"> </p>
<p style="MARGIN: 0px">    <span style="COLOR: blue">protected</span> <span style="COLOR: blue">virtual</span> <span style="COLOR: blue">void</span> OnPropertyChanged(<span style="COLOR: #2b91af">Expression</span>&lt;<span style="COLOR: #2b91af">Func</span>&lt;<span style="COLOR: blue">object</span>&gt;&gt; expression)</p>
<p style="MARGIN: 0px">    {</p>
<p style="MARGIN: 0px">        <span style="COLOR: blue">this</span>.PropertyChanged.Raise(<span style="COLOR: blue">this</span>, expression);</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">event</span> <span style="COLOR: #2b91af">PropertyChangedEventHandler</span> PropertyChanged;</p>
<p style="MARGIN: 0px">}</p>
</div>
<p><!--EndFragment-->Since many developers like to use a base view model class, if the property changed method is put in the base class then children will easily get the support for the lambda expression:</p>
<div style="FONT-FAMILY: Lucida Console; BACKGROUND: white; COLOR: black; FONT-SIZE: 8pt">
<p style="MARGIN: 0px"><span style="COLOR: blue">public</span> <span style="COLOR: blue">abstract</span> <span style="COLOR: blue">class</span> <span style="COLOR: #2b91af">ViewModelBase</span> : <span style="COLOR: #2b91af">INotifyPropertyChanged</span></p>
<p style="MARGIN: 0px">{</p>
<p style="MARGIN: 0px">    <span style="COLOR: blue">public</span> ViewModelBase()</p>
<p style="MARGIN: 0px">    {</p>
<p style="MARGIN: 0px">    }</p>
<p style="MARGIN: 0px"> </p>
<p style="MARGIN: 0px">    <span style="COLOR: blue">protected</span> <span style="COLOR: blue">virtual</span> <span style="COLOR: blue">void</span> OnPropertyChanged(<span style="COLOR: #2b91af">Expression</span>&lt;<span style="COLOR: #2b91af">Func</span>&lt;<span style="COLOR: blue">object</span>&gt;&gt; expression)</p>
<p style="MARGIN: 0px">    {</p>
<p style="MARGIN: 0px">        <span style="COLOR: blue">this</span>.PropertyChanged.Raise(<span style="COLOR: blue">this</span>, expression);</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">event</span> <span style="COLOR: #2b91af">PropertyChangedEventHandler</span> PropertyChanged;</p>
<p style="MARGIN: 0px">}</p>
</div>
<p><!--EndFragment-->The derived class is now a bit more clean.</p>
<div style="FONT-FAMILY: Lucida Console; BACKGROUND: white; COLOR: black; FONT-SIZE: 8pt">
<p style="MARGIN: 0px"><span style="COLOR: blue">public</span> <span style="COLOR: blue">class</span> <span style="COLOR: #2b91af">DummyLambdaViewModel</span> : <span style="COLOR: #2b91af">ViewModelBase</span></p>
<p style="MARGIN: 0px">{</p>
<p style="MARGIN: 0px">    <span style="COLOR: blue">private</span> <span style="COLOR: blue">string</span> _dummyProperty;</p>
<p style="MARGIN: 0px"> </p>
<p style="MARGIN: 0px">    <span style="COLOR: blue">public</span> <span style="COLOR: blue">string</span> DummyProperty</p>
<p style="MARGIN: 0px">    {</p>
<p style="MARGIN: 0px">        <span style="COLOR: blue">get</span></p>
<p style="MARGIN: 0px">        {</p>
<p style="MARGIN: 0px">            <span style="COLOR: blue">return</span> <span style="COLOR: blue">this</span>._dummyProperty;</p>
<p style="MARGIN: 0px">        }</p>
<p style="MARGIN: 0px">        <span style="COLOR: blue">set</span></p>
<p style="MARGIN: 0px">        {</p>
<p style="MARGIN: 0px">            <span style="COLOR: blue">this</span>._dummyProperty = <span style="COLOR: blue">value</span>;</p>
<p style="MARGIN: 0px">            OnPropertyChanged(() =&gt; <span style="COLOR: blue">this</span>.DummyProperty);</p>
<p style="MARGIN: 0px">        }</p>
<p style="MARGIN: 0px">    }</p>
<p style="MARGIN: 0px">}</p>
</div>
<p><!--EndFragment--><strong>References<br />
</strong>The lambda expression code was taken from the following blogs<br />
<a href="http://www.jphamilton.net/post/MVVM-with-Type-Safe-INotifyPropertyChanged.aspx">http://www.jphamilton.net/post/MVVM-with-Type-Safe-INotifyPropertyChanged.aspx</a><br />
<a href="http://blog.decarufel.net/2009/07/how-to-use-inotifypropertychanged-type_22.html">http://blog.decarufel.net/2009/07/how-to-use-inotifypropertychanged-type_22.html</a><br />
<a href="http://consultingblogs.emc.com/merrickchaffer/archive/2010/01/22/a-simple-implementation-of-inotifypropertychanged.aspx">http://consultingblogs.emc.com/merrickchaffer/archive/2010/01/22/a-simple-implementation-of-inotifypropertychanged.aspx</a></p>
<p><strong>Testing without WPF Bindings</strong><br />
There are essentially two components to lambda property change notification that cost performance. The first is the creation of the expression (such as () =&gt; this.DummyProperty). The second is the actual WPF binding infrastructure that affects all of the property change notification implementations. String property change events have virtually no &#8216;expression creation&#8217; processing time since it is just a hard coded string (such as &#8220;DummyProperty&#8221;). By raising property change events when no bindings are attached (and thus no listener to the viewmodel&#8217;s PropertyChanged event), we can compare the &#8216;expression creation&#8217; performance costs of the various property change implementations.</p>
<p><img class="alignnone" src="http://www.quantumbitdesigns.com/blogposts/0022/NoBindingPerformance.png" alt="" width="506" height="423" /></p>
<p>The lambda expressions are roughly 20 times slower than both string INotify and DependencyObjects when the WPF binding infrastructure is not included, giving us a measure of the raw performance cost of just raising the property change event. So far the performance cost of lambda expressions is living up to the &#8216;poor performance&#8217; label.</p>
<p><strong>Testing with WPF Bindings</strong><br />
Since the prior test is only part of the total processing required for property change notification, it is important to test again with a WPF binding in place so that the WPF binding system can work its magic against the property change events. By having a XAML element (such as a TextBlock) bind its Text property to a property of a viewmodel, WPF&#8217;s binding system will now be listening for the property change events and doing its own reflection and internal property management.</p>
<p><img class="alignnone" src="http://www.quantumbitdesigns.com/blogposts/0022/WithBindingPerformance.png" alt="" width="506" height="423" /></p>
<p>Once the WPF binding system is included in the performance tests, the lambda expression implementation drops from 20 times slower to only around 3 times slower. Even though using lambda expressions is slower than the alternatives, testing with the WPF binding system shows the performance hit is probably not as big as many have perceived it to be. Using  property change notification on a DependencyObject is the fastest technique since it was designed for that purpose, allowing the WPF binding system to listen to property change events with virtually no overhead and no reflection. However, like the INotify implementation, it uses a string for the property name identification.</p>
<p><strong>Memory Usage<br />
</strong>Performance is only half the story. In order to make proper design decisions, it is important to also know the memory characteristics of the various property change techniques. By using a profiler we can measure the number of objects created and destroyed, as well as bytes used during each property change request. The WPF binding system is included in the measurements.</p>
<p><img class="alignnone" src="http://www.quantumbitdesigns.com/blogposts/0022/MemoryUsage.png" alt="" width="506" height="423" /></p>
<p>The lambda expressions use almost 7 times the memory as INotify for each property change event, while the DependencyObject property change notification uses no memory at all (but the class itself uses memory). The following screenshot from the profiler shows the WPF binding system objects that are created and destroyed during the INotify event (1,000,000 events):</p>
<p><img class="alignnone" src="http://www.quantumbitdesigns.com/blogposts/0022/INotifyMemoryUsage.png" alt="" width="597" height="88" /></p>
<p>These are the objects and memory used for the lambda expression (1,000,000 events)</p>
<p><img class="alignnone" src="http://www.quantumbitdesigns.com/blogposts/0022/LambdaMemoryUsage.png" alt="" width="595" height="294" /></p>
<p><strong>General Guidelines</strong><br />
With this performance and memory usage information we can summarize some loose guidelines for when to use each property change mechanism. Since the DispatcherObject is a WPF class, it has its own set of memory requirements to support</p>
<ul>
<li><strong>DispatcherObject</strong>: Use if speed critical and frequent property change events occur</li>
<li><strong>INotifyPropertyChanged</strong>: Use if large numbers of viewmodels are created (it is more lightweight than DependencyObject), but speed is also important</li>
<li><strong>Lambda Expressions</strong>: Use for type-safe property change notification when speed is not critical.</li>
</ul>
<p><strong>Test Application</strong><br />
You can download the application and code used for these tests <a href="http://www.quantumbitdesigns.com/blogposts/0022/LambdaPropertyPerformanceApp.zip">here</a>. The code is junk code, and is not a demonstration of proper design, testing, or MVVM principles.</p>
<p><img class="alignnone" src="http://www.quantumbitdesigns.com/blogposts/0022/TestApp.png" alt="" width="367" height="197" /></p>
<p><strong>Disclaimer</strong><br />
These tests were performed using a viewmodel with only one property. Performance can differ on viewmodels with many properties. Tests were also performed by raising the property change notifications in a loop. Real world performance can vary due to <a href="http://en.wikipedia.org/wiki/Locality_of_reference">locality of reference</a>.</p>
<p><a rev="vote-for" href="http://dotnetshoutout.com/Quantum-Bit-Designs-Blog-Archive-MVVM-Lambda-vs-INotifyPropertyChanged-vs-DependencyObject"><img style="border:0px" src="http://dotnetshoutout.com/image.axd?url=http%3A%2F%2Fblog.quantumbitdesigns.com%2F2010%2F01%2F26%2Fmvvm-lambda-vs-inotifypropertychanged-vs-dependencyobject%2F" alt="Shout it" /></a></p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fblog.quantumbitdesigns.com%2f2010%2f01%2f26%2fmvvm-lambda-vs-inotifypropertychanged-vs-dependencyobject%2f"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fblog.quantumbitdesigns.com%2f2010%2f01%2f26%2fmvvm-lambda-vs-inotifypropertychanged-vs-dependencyobject%2f" border="0" alt="kick it on DotNetKicks.com" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.quantumbitdesigns.com/2010/01/26/mvvm-lambda-vs-inotifypropertychanged-vs-dependencyobject/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Article List</title>
		<link>http://blog.quantumbitdesigns.com/2008/07/22/article-list/</link>
		<comments>http://blog.quantumbitdesigns.com/2008/07/22/article-list/#comments</comments>
		<pubDate>Wed, 23 Jul 2008 03:59:55 +0000</pubDate>
		<dc:creator>Kevin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://blog.quantumbitdesigns.com/?p=37</guid>
		<description><![CDATA[2008/07/04 &#8211; A Thread-Safe IDisposable Base Class
2008/06/24 &#8211; DelegateMarshaler &#8211; Replace Control.InvokeRequired and Control.Invoke
2008/06/18 &#8211; Simplifying UI and Worker Threads &#8211; DelegateMarshaler Revisited
2008/06/17 &#8211; Events and Threads
2008/06/10 &#8211; Stop Polluting the UI Thread &#8211; Use a DelegateMarshaler
2008/05/28 &#8211; Bloglist
2008/05/22 &#8211; Programmatically Selecting an Item in a TreeView
2008/04/15 &#8211; QbDirectoryViz
2008/04/05 &#8211; QbColorViz
2008/03/30 &#8211; Simple WPF Progress [...]]]></description>
			<content:encoded><![CDATA[<p>2008/07/04 &#8211; <a href="http://blog.quantumbitdesigns.com/2008/07/22/a-thread-safe-idisposable-base-class/">A Thread-Safe IDisposable Base Class</a><br />
2008/06/24 &#8211; <a href="http://blog.quantumbitdesigns.com/2008/07/22/delegatemarshaler-replace-controlinvokerequired-and-controlinvoke/">DelegateMarshaler &#8211; Replace Control.InvokeRequired and Control.Invoke</a><br />
2008/06/18 &#8211; <a href="http://blog.quantumbitdesigns.com/2008/07/22/simplifying-ui-and-worker-threads-delegatemarshaler-revisited/">Simplifying UI and Worker Threads &#8211; DelegateMarshaler Revisited</a><br />
2008/06/17 &#8211; <a href="http://blog.quantumbitdesigns.com/2008/07/22/events-and-threads/">Events and Threads</a><br />
2008/06/10 &#8211; <a href="http://blog.quantumbitdesigns.com/2008/07/22/stop-polluting-the-ui-thread-use-a-delegatemarshaler/">Stop Polluting the UI Thread &#8211; Use a DelegateMarshaler</a><br />
2008/05/28 &#8211; <a href="http://blog.quantumbitdesigns.com/bloglist/">Bloglist</a><br />
2008/05/22 &#8211; <a href="http://blog.quantumbitdesigns.com/2008/07/22/programmatically-selecting-an-item-in-a-treeview/">Programmatically Selecting an Item in a TreeView</a><br />
2008/04/15 &#8211; <a href="http://blog.quantumbitdesigns.com/qbdirectoryviz/">QbDirectoryViz</a><br />
2008/04/05 &#8211; <a href="http://blog.quantumbitdesigns.com/qbcolorviz/">QbColorViz</a><br />
2008/03/30 &#8211; <a href="http://blog.quantumbitdesigns.com/2008/07/22/simple-wpf-progress-window-with-cancellation/">Simple WPF Progress Window with Cancelation</a><br />
2008/02/10 &#8211; <a href="http://blog.quantumbitdesigns.com/2008/07/22/subtle-multithreading-bugs-part-1/">Subtle Multithreading Bugs &#8211; Part 1</a><br />
2008/01/20 &#8211; <a href="http://blog.quantumbitdesigns.com/2008/07/22/wpf-application-design-and-architecture/">WPF Application Design and Architecture</a><br />
2008/01/06 &#8211; <a href="http://blog.quantumbitdesigns.com/2008/07/22/wpf-cross-thread-collection-binding-part-4-the-grand-solution/">WPF Cross-Thread Collection Binding &#8211; Part 4 &#8211; The Grand Solution</a><br />
2008/01/05 &#8211; <a href="http://blog.quantumbitdesigns.com/2008/07/22/wpf-cross-thread-collection-binding-part-3-working-property-change-events/">WPF Cross-Thread Collection Binding &#8211; Part 3 &#8211; Working Property Change Events</a><br />
2008/01/05 &#8211; <a href="http://blog.quantumbitdesigns.com/2008/07/22/wpf-cross-thread-collection-binding-part-2-property-change-events/">WPF Cross-Thread Collection Binding &#8211; Part 2 &#8211; Property Change Events</a><br />
2008/01/01 &#8211; <a href="http://blog.quantumbitdesigns.com/2008/07/22/wpf-cross-thread-collection-binding-part-1/">WPF Cross-Thread Collection Binding &#8211; Part 1</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.quantumbitdesigns.com/2008/07/22/article-list/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A Thread-Safe IDisposable Base Class</title>
		<link>http://blog.quantumbitdesigns.com/2008/07/22/a-thread-safe-idisposable-base-class/</link>
		<comments>http://blog.quantumbitdesigns.com/2008/07/22/a-thread-safe-idisposable-base-class/#comments</comments>
		<pubDate>Wed, 23 Jul 2008 03:47:49 +0000</pubDate>
		<dc:creator>Kevin</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Threadsafety]]></category>

		<guid isPermaLink="false">http://blog.quantumbitdesigns.com/?p=35</guid>
		<description><![CDATA[Davy Brion is in the same situation as me. Every time we need to implement IDisposable (rarely) we have to look up the recommended pattern. Therefore he came up with an abstract base class that provides the proper plumbing and method signatures. All it takes is deriving from this utility class and overriding the DisposeManagedResources() [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://davybrion.com/blog">Davy Brion</a> is in the same situation as me. Every time we need to implement IDisposable (rarely) we have to look up the recommended pattern. Therefore he came up with an <a href="http://davybrion.com/blog/2008/06/disposing-of-the-idisposable-implementation/">abstract base class</a> that provides the proper plumbing and method signatures. All it takes is deriving from this utility class and overriding the DisposeManagedResources() method, and you have your IDisposable class. Obviously deriving from a utility class does not fit every scenario, but it works great for most of my needs.</p>
<p>I liked the idea so much that I decided to take it a bit further and make it &#8216;Thread-Safe&#8217;. In other words, any thread can call Dispose() on an object that derives from the following ManagedDisposable class, and the dispose plumbing will only execute once. The class is not actually thread-safe</p>
<p><strong>The ManagedDisposable Implementation:</strong></p>
<p style="margin: 0px">    <span style="color: blue">public</span> <span style="color: blue">abstract</span> <span style="color: blue">class</span> <span style="color: #2b91af">ManagedDisposable</span> : <span style="color: #2b91af">IDisposable</span></p>
<p style="margin: 0px">    {</p>
<p style="margin: 0px">        <span style="color: blue">private</span> <span style="color: blue">int</span> _disposed;</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px">        <span style="color: blue">protected</span> ManagedDisposable()</p>
<p style="margin: 0px">        {</p>
<p style="margin: 0px">            <span style="color: blue">this</span>._disposed = 0;</p>
<p style="margin: 0px">        }</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px">        <span style="color: blue">public</span> <span style="color: blue">bool</span> IsDisposed</p>
<p style="margin: 0px">        {</p>
<p style="margin: 0px">            <span style="color: blue">get</span></p>
<p style="margin: 0px">            {</p>
<p style="margin: 0px">                <span style="color: blue">return</span> <span style="color: blue">this</span>._disposed == 1;</p>
<p style="margin: 0px">            }</p>
<p style="margin: 0px">        }</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px">        <span style="color: blue">public</span> <span style="color: blue">void</span> Dispose()</p>
<p style="margin: 0px">        {</p>
<p style="margin: 0px">            Dispose(<span style="color: blue">true</span>);</p>
<p style="margin: 0px">            <span style="color: #2b91af">GC</span>.SuppressFinalize(<span style="color: blue">this</span>);</p>
<p style="margin: 0px">        }</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px">        <span style="color: blue">protected</span> <span style="color: blue">virtual</span> <span style="color: blue">void</span> Dispose(<span style="color: blue">bool</span> disposing)</p>
<p style="margin: 0px">        {</p>
<p style="margin: 0px">            <span style="color: blue">if</span> (<span style="color: #2b91af">Interlocked</span>.CompareExchange(<span style="color: blue">ref</span> <span style="color: blue">this</span>._disposed, 1, 0) == 0)</p>
<p style="margin: 0px">            {</p>
<p style="margin: 0px">                <span style="color: blue">if</span> (disposing)</p>
<p style="margin: 0px">                {</p>
<p style="margin: 0px">                    DisposeManagedResources();</p>
<p style="margin: 0px">                }</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px">                DisposeUnmanagedResources();</p>
<p style="margin: 0px">            }</p>
<p style="margin: 0px">        }</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px">        <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;summary&gt;</span></p>
<p style="margin: 0px">        <span style="color: gray">///</span><span style="color: green"> Helper method so subclasses can easily throw if disposed</span></p>
<p style="margin: 0px">        <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;/summary&gt;</span></p>
<p style="margin: 0px">        <span style="color: blue">protected</span> <span style="color: blue">void</span> ThrowIfDisposed()</p>
<p style="margin: 0px">        {</p>
<p style="margin: 0px">            <span style="color: blue">if</span> (<span style="color: blue">this</span>.IsDisposed == <span style="color: blue">true</span>)</p>
<p style="margin: 0px">            {</p>
<p style="margin: 0px">                <span style="color: blue">throw</span> <span style="color: blue">new</span> <span style="color: #2b91af">ObjectDisposedException</span>(<span style="color: blue">this</span>.GetType().FullName);</p>
<p style="margin: 0px">            }</p>
<p style="margin: 0px">        }</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px">        <span style="color: blue">protected</span> <span style="color: blue">virtual</span> <span style="color: blue">void</span> DisposeManagedResources()</p>
<p style="margin: 0px">        {</p>
<p style="margin: 0px">        }</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px">        <span style="color: blue">protected</span> <span style="color: blue">virtual</span> <span style="color: blue">void</span> DisposeUnmanagedResources()</p>
<p style="margin: 0px">        {</p>
<p style="margin: 0px">        }</p>
<p style="margin: 0px">    }</p>
<p><!--EndFragment--></p>
<p style="margin: 0px"><strong>Derived Class Example:</strong></p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px">    <span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">MyThreadingObject</span> : <span style="color: #2b91af">ManagedDisposable</span></p>
<p style="margin: 0px">    {</p>
<p style="margin: 0px">        <span style="color: blue">private</span> <span style="color: #2b91af">SharedResource</span> _sharedResource;</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px">        <span style="color: blue">public</span> MyThreadingObject()</p>
<p style="margin: 0px">        {</p>
<p style="margin: 0px">        }</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px">        <span style="color: blue">public</span> <span style="color: blue">void</span> Start()</p>
<p style="margin: 0px">        {</p>
<p style="margin: 0px">            <span style="color: #2b91af">Thread</span> thread = <span style="color: blue">new</span> <span style="color: #2b91af">Thread</span>(ThreadMethod);</p>
<p style="margin: 0px">            thread.Start();</p>
<p style="margin: 0px">        }</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px">        <span style="color: blue">private</span> <span style="color: blue">void</span> ThreadMethod()</p>
<p style="margin: 0px">        {</p>
<p style="margin: 0px">            <span style="color: blue">this</span>._sharedResource = <span style="color: blue">new</span> <span style="color: #2b91af">SharedResource</span>();</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px">            <span style="color: blue">for</span> (<span style="color: blue">int</span> i = 0; i &lt; 10; ++i)</p>
<p style="margin: 0px">            {</p>
<p style="margin: 0px">                <span style="color: #2b91af">SharedResource</span> sharedResource = <span style="color: blue">this</span>._sharedResource;</p>
<p style="margin: 0px">                <span style="color: blue">if</span> (sharedResource != <span style="color: blue">null</span>)</p>
<p style="margin: 0px">                {</p>
<p style="margin: 0px">                    <span style="color: blue">lock</span> (sharedResource)</p>
<p style="margin: 0px">                    {</p>
<p style="margin: 0px">                        <span style="color: green">//do some work</span></p>
<p style="margin: 0px">                        <span style="color: green">//sharedResource.Process();</span></p>
<p style="margin: 0px">                    }</p>
<p style="margin: 0px">                }</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px">                <span style="color: #2b91af">Thread</span>.Sleep(1000); <span style="color: green">//do some other work</span></p>
<p style="margin: 0px">            }</p>
<p style="margin: 0px">        }</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px">        <span style="color: blue">protected</span> <span style="color: blue">override</span> <span style="color: blue">void</span> DisposeManagedResources()</p>
<p style="margin: 0px">        {</p>
<p style="margin: 0px">            <span style="color: #2b91af">SharedResource</span> sharedResource = <span style="color: blue">this</span>._sharedResource;</p>
<p style="margin: 0px">&nbsp;</p>
<p style="margin: 0px">            <span style="color: blue">if</span> (sharedResource != <span style="color: blue">null</span>)</p>
<p style="margin: 0px">            {</p>
<p style="margin: 0px">                <span style="color: blue">lock</span> (sharedResource)</p>
<p style="margin: 0px">                {</p>
<p style="margin: 0px">                    sharedResource.Dispose();</p>
<p style="margin: 0px">                    <span style="color: blue">this</span>._sharedResource = <span style="color: blue">null</span>;</p>
<p style="margin: 0px">                }</p>
<p style="margin: 0px">            }</p>
<p style="margin: 0px">        }</p>
<p style="margin: 0px">    }</p>
<p>Notice how there is another element to making the implementation thread-safe. Derived classes still need to protect access to their shared resource(s) via a lock. In the case above, a lock is acquired each time the SharedResource is accessed. If such a lock did not exist, then a race condition could exist where the DisposeManagedResources() is called from another thread (disposing and setting the _sharedResource to null) while the ThreadMethod() attempts to use the resource.</p>
<p>Some may also have noticed how there is no finalizer method in the ManagedDisposable. This is because there are significant costs associated with finalization. If a finalizer is needed, use this class instead:</p>
<p><strong>UnManagedDisposable Implementation</strong></p>
<p style="margin: 0px">    <span style="color: blue">public</span> <span style="color: blue">abstract</span> <span style="color: blue">class</span> <span style="color: #2b91af">UnManagedDisposable</span> : <span style="color: #2b91af">ManagedDisposable</span></p>
<p style="margin: 0px">    {</p>
<p style="margin: 0px">        <span style="color: green">// Use C# destructor syntax for finalization code. </span></p>
<p style="margin: 0px">        <span style="color: green">// This destructor will run only if the Dispose method </span></p>
<p style="margin: 0px">        <span style="color: green">// does not get called. </span></p>
<p style="margin: 0px">        <span style="color: green">// It gives your base class the opportunity to finalize. </span></p>
<p style="margin: 0px">        <span style="color: green">// Do not provide destructors in types derived from this class. </span></p>
<p style="margin: 0px">        ~UnManagedDisposable()</p>
<p style="margin: 0px">        {</p>
<p style="margin: 0px">            Dispose(<span style="color: blue">false</span>);</p>
<p style="margin: 0px">        }</p>
<p style="margin: 0px">    }</p>
<p><!--EndFragment-->Ultimately if you are using unmanaged resources you can still use the first implementation, it just means the developer is completely responsible for calling the Dispose() method to release both managed and unmanaged resources. Otherwise the unmanaged resources will be leaked. If the second class is used, then even if a developer does not call Dispose() the destructor will eventually be called [Dispose(false) which will call DisposeUnmanagedResources()] by the garbage collector. A quick performance test indicated that ManagedDisposable is 5 times faster than UnManagedDisposable (when Dispose is not called).</p>
<p>An example of something that would ideally implement the UnManagedDisposable is the .NET Font class. If you use fonts and do not call Dispose(), the garbage collector will clean up after you eventually and free the unmanaged font resources. Really fonts should be disposed once they are no longer in use to immediately free these unmanaged resources, but the truth is thousands of developers and components do not always follow this suggestion.</p>
<p>If you don&#8217;t like two classes, just copy thr destructor code into the ManagedDisposable (and perhaps give it a better name).</p>
<p><strong>Resources</strong></p>
<ul>
<li><a href="http://www.bluebytesoftware.com/blog/2008/02/18/IDisposableFinalizationAndConcurrency.aspx">IDisposable, finalization, and concurrency </a></li>
<li><a href="http://www.bluebytesoftware.com/blog/2005/04/08/DGUpdateDisposeFinalizationAndResourceManagement.aspx">DG Update: Dispose, Finalization, and Resource Management</a></li>
<li><a href="http://blogs.msdn.com/cbrumme/archive/2004/02/20/77460.aspx">Finalization</a> (old)</li>
<li><a href="http://msdn.microsoft.com/en-us/library/fs2xkftw.aspx">Implementing a Dispose Method</a></li>
<li><a href="http://www.devx.com/dotnet/Article/33167/1954">When and how to Use Dispose and Finalize in C#</a></li>
</ul>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fblog.quantumbitdesigns.com%2f2008%2f07%2f10%2fa-thread-safe-idisposable-base-class%2f"><img border="0" src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fblog.quantumbitdesigns.com%2f2008%2f07%2f10%2fa-thread-safe-idisposable-base-class%2f" alt="kick it on DotNetKicks.com" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.quantumbitdesigns.com/2008/07/22/a-thread-safe-idisposable-base-class/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>DelegateMarshaler &#8211; Replace Control.InvokeRequired and Control.Invoke</title>
		<link>http://blog.quantumbitdesigns.com/2008/07/22/delegatemarshaler-replace-controlinvokerequired-and-controlinvoke/</link>
		<comments>http://blog.quantumbitdesigns.com/2008/07/22/delegatemarshaler-replace-controlinvokerequired-and-controlinvoke/#comments</comments>
		<pubDate>Wed, 23 Jul 2008 03:44:06 +0000</pubDate>
		<dc:creator>Kevin</dc:creator>
				<category><![CDATA[Multithreading]]></category>
		<category><![CDATA[DelegateMarshaler]]></category>
		<category><![CDATA[Design]]></category>

		<guid isPermaLink="false">http://blog.quantumbitdesigns.com/?p=33</guid>
		<description><![CDATA[This is the third visitation of the topic of UI and worker thread interaction. Based upon excellent feedback through the comments (thanks Peter Ritchie and others) I have renamed and modified the previous ThreadBarrier implementation (which was a poor name to begin with since a thread barrier concept already represents something else). The previous pattern [...]]]></description>
			<content:encoded><![CDATA[<p><!--StartFragment -->This is the third visitation of the topic of UI and worker thread interaction. Based upon excellent feedback through the comments (thanks <a href="http://msmvps.com/Blogs/PeterRitchie/">Peter Ritchie</a> and others) I have renamed and modified the previous ThreadBarrier implementation (which was a poor name to begin with since a thread barrier concept already represents something else). The previous pattern of encapsulating a thread and communicating to the UI via events raised on the UI thread is still my recommendation: see the <a href="http://blog.quantumbitdesigns.com/2008/07/22/stop-polluting-the-ui-thread-use-a-delegatemarshaler/">first post</a> for a long winded explanation, and the <a href="http://blog.quantumbitdesigns.com/2008/07/22/simplifying-ui-and-worker-threads-delegatemarshaler-revisited/">second post</a> for more examples. However, there are many people that already have existing code that uses the Control.InvokeRequired and Control.Invoke pattern such as:</p>
<p style="margin: 0px"><span style="color: #0000ff;">delegate</span> <span style="color: #0000ff;">void</span> <span style="color: #2b91af;">UpdateProgressDelegate</span>(<span style="color: #0000ff;">int</span> progress);</p>
<p style="margin: 0px"> </p>
<p style="margin: 0px"><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">void</span> UpdateProgressBar(<span style="color: #0000ff;">int</span> progress)</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">if</span> (<span style="color: #0000ff;">this</span>.InvokeRequired == <span style="color: #0000ff;">false</span>)</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>.progressBarDownload.Value = progress;</p>
<p style="margin: 0px">}</p>
<p style="margin: 0px"><span style="color: #0000ff;">else</span></p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>.Invoke(<span style="color: #0000ff;">new</span> <span style="color: #2b91af;">UpdateProgressDelegate</span>(UpdateProgressBar), <span style="color: #0000ff;">new</span> <span style="color: #0000ff;">object</span>[] { progress });</p>
<p style="margin: 0px">}</p>
<p style="margin: 0px">}</p>
<p>The new implementation is intended to replace this code and support the original ThreadBarrier concept.</p>
<p><big><big><span style="font-weight: bold">Introducing the DelegateMarshaler</span><br style="font-weight: bold" /></big></big><br />
The DelegateMarshaler implementation is virtually identical to the ThreadBarrier except for four minor differences:</p>
<ol>
<li>The marshaler is created using a static method DelegateMarshaler.Create() so an exception can be thrown if no SynchronizationContext exists (console app, or before UI is started, etc.)</li>
<li>If the calling thread is already the target thread (UI thread), then the delegate is invoked normally rather than a cross thread invoke. This is similar to InvokeRequired being false.</li>
<li>The DelegateMarshaler supports methods with 0 to 4 arguments.</li>
<li>Static methods wrap ThreadPool.QueueUserWorkItem in a type safe way.</li>
</ol>
<p><strong>A compact example</strong></p>
<p style="margin: 0px"><span style="color: #0000ff;">void</span> buttonDownload_Click(<span style="color: #0000ff;">object</span> sender, <span style="color: #2b91af;">EventArgs</span> e)</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #2b91af;">DelegateMarshaler</span> marshaler = <span style="color: #2b91af;">DelegateMarshaler</span>.Create();</p>
<p style="margin: 0px"> </p>
<p style="margin: 0px"><span style="color: #2b91af;">DelegateMarshaler</span>.QueueOnThreadPoolThread(</p>
<p style="margin: 0px">(fileName) =&gt;</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #008000;">//simulate download</span></p>
<p style="margin: 0px"><span style="color: #0000ff;">for</span> (<span style="color: #0000ff;">int</span> i = 0; i &lt; 100; ++i)</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px">marshaler.Invoke(UpdateProgressBar, i);</p>
<p style="margin: 0px"><span style="color: #2b91af;">Thread</span>.Sleep(50);</p>
<p style="margin: 0px">}</p>
<p style="margin: 0px">marshaler.Invoke(ShowDownloadComplete, fileName);</p>
<p style="margin: 0px">},</p>
<p style="margin: 0px"><span style="color: #a31515;">&#8220;somefile.txt&#8221;</span>);</p>
<p style="margin: 0px">}</p>
<p style="margin: 0px"> </p>
<p style="margin: 0px"><span style="color: #0000ff;">private</span> <span style="color: #0000ff;">void</span> UpdateProgressBar(<span style="color: #0000ff;">int</span> progress)</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>.progressBarDownload.Value = progress;</p>
<p style="margin: 0px">}</p>
<p style="margin: 0px"> </p>
<p style="margin: 0px"><span style="color: #0000ff;">private</span> <span style="color: #0000ff;">void</span> ShowDownloadComplete(<span style="color: #0000ff;">string</span> fileName)</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>.labelFileDownload.Text = fileName;</p>
<p style="margin: 0px">}</p>
<p>Using the DelegateMarshaler consists of creating the marshaler on the UI thread and invoking the methods that update the UI (preferably from the worker thread). Invoke will call the method synchronously, and BeginInvoke will call the method asynchronously allowing the worker to continue running while the UI updates. If your thread is a separate method altogether (which is usually the case), you would want to save the DelegateMarshaler instance as a private field in your form or control so it can be used in the thread method.</p>
<p><big><big><span style="font-weight: bold">The DelegateMarshaler Implementation</span></big></big></p>
<p style="margin: 0px"><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">sealed</span> <span style="color: #0000ff;">class</span> <span style="color: #2b91af;">DelegateMarshaler</span></p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">private</span> <span style="color: #2b91af;">SynchronizationContext</span> _synchronizationContext;</p>
<p style="margin: 0px"> </p>
<p style="margin: 0px"><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span> <span style="color: #2b91af;">DelegateMarshaler</span> Create()</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">if</span> (<span style="color: #2b91af;">SynchronizationContext</span>.Current == <span style="color: #0000ff;">null</span>)</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">throw</span> <span style="color: #0000ff;">new</span> <span style="color: #2b91af;">InvalidOperationException</span>(<span style="color: #a31515;">&#8220;No SynchronizationContext exists for the current thread.&#8221;</span>);</p>
<p style="margin: 0px">}</p>
<p style="margin: 0px"><span style="color: #0000ff;">return</span> <span style="color: #0000ff;">new</span> <span style="color: #2b91af;">DelegateMarshaler</span>(<span style="color: #2b91af;">SynchronizationContext</span>.Current);</p>
<p style="margin: 0px">}</p>
<p style="margin: 0px"> </p>
<p style="margin: 0px"><span style="color: #0000ff;">private</span> DelegateMarshaler(<span style="color: #2b91af;">SynchronizationContext</span> synchronizationContext)</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>._synchronizationContext = synchronizationContext;</p>
<p style="margin: 0px">}</p>
<p style="margin: 0px"> </p>
<p style="margin: 0px"><span style="color: #0000ff;">private</span> <span style="color: #0000ff;">bool</span> IsMarshalRequired</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">get</span></p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">return</span> <span style="color: #0000ff;">this</span>._synchronizationContext != <span style="color: #2b91af;">SynchronizationContext</span>.Current;</p>
<p style="margin: 0px">}</p>
<p style="margin: 0px">}</p>
<p style="margin: 0px"> </p>
<p style="margin: 0px"><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">void</span> Invoke&lt;T&gt;(<span style="color: #2b91af;">Action</span>&lt;T&gt; action, T arg)</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">if</span> (<span style="color: #0000ff;">this</span>.IsMarshalRequired == <span style="color: #0000ff;">false</span>)</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #008000;">// already on the target thread, just invoke delegate directly</span></p>
<p style="margin: 0px">action(arg);</p>
<p style="margin: 0px">}</p>
<p style="margin: 0px"><span style="color: #0000ff;">else</span></p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #008000;">// marshal the delegate call to the target thread</span></p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>._synchronizationContext.Send(<span style="color: #0000ff;">delegate</span> { action(arg); }, <span style="color: #0000ff;">null</span>);</p>
<p style="margin: 0px">}</p>
<p style="margin: 0px">}</p>
<p style="margin: 0px"> </p>
<p style="margin: 0px"><span style="color: #008000;">//simplifies use of threadpool so arguments do not need to be cast</span></p>
<p style="margin: 0px"><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span> <span style="color: #0000ff;">void</span> QueueOnThreadPoolThread&lt;T&gt;(<span style="color: #2b91af;">Action</span>&lt;T&gt; action, T arg)</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #2b91af;">ThreadPool</span>.QueueUserWorkItem(<span style="color: #0000ff;">delegate</span> { action(arg); });</p>
<p style="margin: 0px">}</p>
<p style="margin: 0px">}</p>
<p>It is such a small class, feel free to modify it to fit your needs. Download the sample for the complete code and comments:</p>
<p><a href="http://www.quantumbitdesigns.com/blogposts/0020/files/DelegateMarshalerSample.zip"><span style="font-weight: bold">DelegateMarshalerSample</span></a></p>
<p><span style="font-weight: bold">Notable Links</span><br style="font-weight: bold" /><span style="font-size: 11pt; font-family: 'Calibri','sans-serif';"><a href="http://thevalerios.net/matt/2008/05/a-type-safe-backgroundworker-wrapper/">http://thevalerios.net/matt/2008/05/a-type-safe-backgroundworker-wrapper/</a><br />
</span><span style="font-size: 11pt; font-family: 'Calibri','sans-serif';"><a href="http://weblogs.asp.net/justin_rogers/articles/126345.aspx">http://weblogs.asp.net/justin_rogers/articles/126345.aspx</a><br />
</span><span style="font-size: 11pt; font-family: 'Calibri','sans-serif';"><a href="http://www.codeproject.com/KB/cs/AOPInvokeRequired.aspx">http://www.codeproject.com/KB/cs/AOPInvokeRequired.aspx</a></span></p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fblog.quantumbitdesigns.com%2f2008%2f06%2f24%2fdelegatemarshaler-replace-controlinvokerequired-and-controlinvoke%2f"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fblog.quantumbitdesigns.com%2f2008%2f06%2f24%2fdelegatemarshaler-replace-controlinvokerequired-and-controlinvoke%2f" border="0" alt="kick it on DotNetKicks.com" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.quantumbitdesigns.com/2008/07/22/delegatemarshaler-replace-controlinvokerequired-and-controlinvoke/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

