<?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 &#187; Design</title>
	<atom:link href="http://blog.quantumbitdesigns.com/tag/design/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>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>
		<item>
		<title>Simplifying UI and Worker Threads &#8211; DelegateMarshaler Revisited</title>
		<link>http://blog.quantumbitdesigns.com/2008/07/22/simplifying-ui-and-worker-threads-delegatemarshaler-revisited/</link>
		<comments>http://blog.quantumbitdesigns.com/2008/07/22/simplifying-ui-and-worker-threads-delegatemarshaler-revisited/#comments</comments>
		<pubDate>Wed, 23 Jul 2008 03:41:44 +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=30</guid>
		<description><![CDATA[Background
Update &#8211; ThreadBarrier was a poorly chosen name, use the latest DelegateMarshaler implementation instead.
Previously I introduced the ThreadBarrier pattern which describes a simple technique for allowing worker threads to easily and safely communicate with controls on the UI thread. The key points from the previous article are:
A worker thread is completely contained within a class [...]]]></description>
			<content:encoded><![CDATA[<p><big><big><span style="font-weight: bold">Background</span></big></big></p>
<p><strong>Update</strong> &#8211; ThreadBarrier was a poorly chosen name, use the latest <a href="http://blog.quantumbitdesigns.com/2008/07/22/delegatemarshaler-replace-controlinvokerequired-and-controlinvoke/">DelegateMarshaler</a> implementation instead.</p>
<p>Previously I introduced the <a href="http://blog.quantumbitdesigns.com/2008/07/22/stop-polluting-the-ui-thread-use-a-delegatemarshaler/">ThreadBarrier pattern</a> which describes a simple technique for allowing worker threads to easily and safely communicate with controls on the UI thread. The key points from the previous article are:</p>
<p>A worker thread is completely contained within a class (and any objects the class references)</p>
<ol>
<li>Events from this worker class are raised on the UI thread</li>
<li>A SynchronizationContext is used rather than Control.Invoke or Dispatcher.Invoke</li>
<li>The UI code does not have to worry about what thread is executing, it always assumes the UI thread (keeps code clean)</li>
<li>The ThreadBarrier needs to be created on a UI thread to capture the UI&#8217;s SynchronizationContext</li>
</ol>
<p>Today&#8217;s article is a revisitation of the pattern to demonstrate several ways the technique can be used, as well as describe the flaw in the previous implementation. Yesterday&#8217;s article on <a href="http://blog.quantumbitdesigns.com/2008/07/22/events-and-threads/">events and threads</a> provides an in depth background on the subtleties of events and multithreading. The contents of today&#8217;s post include:</p>
<ul>
<li>The New ThreadBarrier Code</li>
<li>Sample UI and Worker Classes</li>
<li>ThreadBarrier Technique #1: Subclassing an existing worker thread class</li>
<li>ThreadBarrier Technique #2: Using extension methods on a SynchronizationContext</li>
<li>ThreadBarrier Technique #3: Deriving from a ThreadBarrier</li>
<li>ThreadBarrier Technique #4: Creating an instance of a ThreadBarrier</li>
<li>ThreadBarrier Technique #5: Creating an adapter class to propagate events</li>
<li>The Original ThreadBarrier Implementation Flaw</li>
<li>ThreadBarrier FAQ</li>
</ul>
<p><a style="font-weight: bold" href="http://www.quantumbitdesigns.com/blogposts/0019/files/ThreadBarrierExamples.zip">Download the examples</a><span style="font-weight: bold">.</span></p>
<p><big><big><span style="font-weight: bold">The New ThreadBarrier Code<br />
</span></big></big><br />
<span style="font-weight: bold">.NET 2.0</span></p>
<p><!-- {\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;\red0\green0\blue255;\red43\green145\blue175;\red128\green128\blue128;\red0\green128\blue0;}??\fs16     \cf3 public\cf0  \cf3 class\cf0  \cf4 ThreadBarrier\par ??\cf0     \{\par ??        \cf5 ///\cf6  \cf5 &amp;lt;summary&amp;gt;\par ??\cf0         \cf5 ///\cf6  The ThreadBarrier's captured SynchronizationContext\par ??\cf0         \cf5 ///\cf6  \cf5 &amp;lt;/summary&amp;gt;\par ??\cf0         \cf3 private\cf0  \cf4 SynchronizationContext\cf0  _synchronizationContext;\par ??\par ??        \cf5 ///\cf6  \cf5 &amp;lt;summary&amp;gt;\par ??\cf0         \cf5 ///\cf6  Captures the current thread's SynchronizationContext\par ??\cf0         \cf5 ///\cf6  \cf5 &amp;lt;/summary&amp;gt;\par ??\cf0         \cf3 public\cf0  ThreadBarrier()\par ??        \{\par ??            \cf3 this\cf0 ._synchronizationContext = \cf4 AsyncOperationManager\cf0 .SynchronizationContext;\par ??        \}\par ??\par ??        \cf3 public\cf0  \cf3 void\cf0  Post&amp;lt;T&amp;gt;(T e, \cf4 Action\cf0 &amp;lt;T&amp;gt; raiseEventMethod)\par ??            \cf3 where\cf0  T : \cf4 EventArgs\par ??\cf0         \{\par ??            \cf3 if\cf0  (\cf3 this\cf0 ._synchronizationContext == \cf3 null\cf0 )\par ??            \{\par ??                \cf4 ThreadPool\cf0 .QueueUserWorkItem(\cf3 delegate\cf0  \{ raiseEventMethod(e); \});\par ??            \}\par ??            \cf3 else\par ??\cf0             \{\par ??                \cf3 this\cf0 ._synchronizationContext.Post(\cf3 delegate\cf0  \{ raiseEventMethod(e); \}, \cf3 null\cf0 );\par ??            \}\par ??        \}\par ??\par ??        \cf3 public\cf0  \cf3 void\cf0  Send&amp;lt;T&amp;gt;(T e, \cf4 Action\cf0 &amp;lt;T&amp;gt; raiseEventMethod)\par ??            \cf3 where\cf0  T : \cf4 EventArgs\par ??\cf0         \{\par ??            \cf3 if\cf0  (\cf3 this\cf0 ._synchronizationContext == \cf3 null\cf0 )\par ??            \{\par ??                raiseEventMethod(e);\par ??            \}\par ??            \cf3 else\par ??\cf0             \{\par ??                \cf3 this\cf0 ._synchronizationContext.Send(\cf3 delegate\cf0  \{ raiseEventMethod(e); \}, \cf3 null\cf0 );\par ??            \}\par ??        \}\par ??    \}} --></p>
<p style="font-size: 8pt; background: white 0% 50%; color: black; font-family: Courier New; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial"><!-- {\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;\red0\green0\blue255;\red43\green145\blue175;\red128\green128\blue128;\red0\green128\blue0;}??\fs16     \cf3 public\cf0  \cf3 class\cf0  \cf4 ThreadBarrier\par ??\cf0     \{\par ??        \cf5 ///\cf6  \cf5 &amp;lt;summary&amp;gt;\par ??\cf0         \cf5 ///\cf6  The ThreadBarrier's captured SynchronizationContext\par ??\cf0         \cf5 ///\cf6  \cf5 &amp;lt;/summary&amp;gt;\par ??\cf0         \cf3 private\cf0  \cf4 SynchronizationContext\cf0  _synchronizationContext;\par ??\par ??        \cf5 ///\cf6  \cf5 &amp;lt;summary&amp;gt;\par ??\cf0         \cf5 ///\cf6  Captures the current thread's SynchronizationContext\par ??\cf0         \cf5 ///\cf6  \cf5 &amp;lt;/summary&amp;gt;\par ??\cf0         \cf3 public\cf0  ThreadBarrier()\par ??        \{\par ??            \cf3 this\cf0 ._synchronizationContext = \cf4 AsyncOperationManager\cf0 .SynchronizationContext;\par ??        \}\par ??\par ??        \cf3 public\cf0  \cf3 void\cf0  Post&amp;lt;T&amp;gt;(\cf4 Action\cf0 &amp;lt;T&amp;gt; raiseEventMethod, T e)\par ??            \cf3 where\cf0  T : \cf4 EventArgs\par ??\cf0         \{\par ??            \cf3 if\cf0  (\cf3 this\cf0 ._synchronizationContext == \cf3 null\cf0 )\par ??            \{\par ??                \cf4 ThreadPool\cf0 .QueueUserWorkItem(\cf3 delegate\cf0  \{ raiseEventMethod(e); \});\par ??            \}\par ??            \cf3 else\par ??\cf0             \{\par ??                \cf3 this\cf0 ._synchronizationContext.Post(\cf3 delegate\cf0  \{ raiseEventMethod(e); \}, \cf3 null\cf0 );\par ??            \}\par ??        \}\par ??\par ??        \cf3 public\cf0  \cf3 void\cf0  Send&amp;lt;T&amp;gt;(\cf4 Action\cf0 &amp;lt;T&amp;gt; raiseEventMethod, T e)\par ??            \cf3 where\cf0  T : \cf4 EventArgs\par ??\cf0         \{\par ??            \cf3 if\cf0  (\cf3 this\cf0 ._synchronizationContext == \cf3 null\cf0 )\par ??            \{\par ??                raiseEventMethod(e);\par ??            \}\par ??            \cf3 else\par ??\cf0             \{\par ??                \cf3 this\cf0 ._synchronizationContext.Send(\cf3 delegate\cf0  \{ raiseEventMethod(e); \}, \cf3 null\cf0 );\par ??            \}\par ??        \}\par ??    \}} --></p>
<p style="margin: 0px"><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span> <span style="color: #2b91af;">ThreadBarrier</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> ThreadBarrier()</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>._synchronizationContext = <span style="color: #2b91af;">AsyncOperationManager</span>.SynchronizationContext;</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> Post&lt;T&gt;(<span style="color: #2b91af;">Action</span>&lt;T&gt; raiseEventMethod, T e)</p>
<p style="margin: 0px"><span style="color: #0000ff;">where</span> T : <span style="color: #2b91af;">EventArgs</span></p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">if</span> (<span style="color: #0000ff;">this</span>._synchronizationContext == <span style="color: #0000ff;">null</span>)</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #2b91af;">ThreadPool</span>.QueueUserWorkItem(<span style="color: #0000ff;">delegate</span> { raiseEventMethod(e); });</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>._synchronizationContext.Post(<span style="color: #0000ff;">delegate</span> { raiseEventMethod(e); }, <span style="color: #0000ff;">null</span>);</p>
<p style="margin: 0px">}</p>
<p style="margin: 0px">}</p>
<p>}</p>
<p><span style="font-weight: bold">.NET 3.5</span></p>
<p><!-- {\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;\red0\green0\blue255;\red43\green145\blue175;}??\fs16     \cf3 public\cf0  \cf3 static\cf0  \cf3 class\cf0  \cf4 ThreadBarrierExtensions\par ??\cf0     \{\par ??        \cf3 public\cf0  \cf3 static\cf0  \cf3 void\cf0  Post&amp;lt;T&amp;gt;(\cf3 this\cf0  \cf4 SynchronizationContext\cf0  synchronizationContext, \cf4 Action\cf0 &amp;lt;T&amp;gt; raiseEventMethod, T eventArgs)\par ??            \cf3 where\cf0  T : \cf4 EventArgs\par ??\cf0         \{\par ??            \cf3 if\cf0  (synchronizationContext == \cf3 null\cf0 )\par ??            \{\par ??                \cf4 ThreadPool\cf0 .QueueUserWorkItem((e) =&amp;gt; raiseEventMethod((T)e), eventArgs);\par ??            \}\par ??            \cf3 else\par ??\cf0             \{\par ??                synchronizationContext.Post((e) =&amp;gt; raiseEventMethod((T)e), eventArgs);\par ??            \}\par ??        \}\par ??\par ??        \cf3 public\cf0  \cf3 static\cf0  \cf3 void\cf0  Send&amp;lt;T&amp;gt;(\cf3 this\cf0  \cf4 SynchronizationContext\cf0  synchronizationContext, \cf4 Action\cf0 &amp;lt;T&amp;gt; raiseEventMethod, T eventArgs)\par ??            \cf3 where\cf0  T : \cf4 EventArgs\par ??\cf0         \{\par ??            \cf3 if\cf0  (synchronizationContext == \cf3 null\cf0 )\par ??            \{\par ??                raiseEventMethod(eventArgs);\par ??            \}\par ??            \cf3 else\par ??\cf0             \{\par ??                synchronizationContext.Send((e) =&amp;gt; raiseEventMethod((T)e), eventArgs);\par ??            \}\par ??        \}\par ??    \}} --></p>
<p style="margin: 0px"><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span> <span style="color: #0000ff;">class</span> <span style="color: #2b91af;">ThreadBarrierExtensions</span></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: #0000ff;">void</span> Post&lt;T&gt;(<span style="color: #0000ff;">this</span> <span style="color: #2b91af;">SynchronizationContext</span> synchronizationContext, <span style="color: #2b91af;">Action</span>&lt;T&gt; raiseEventMethod, T eventArgs)</p>
<p style="margin: 0px"><span style="color: #0000ff;">where</span> T : <span style="color: #2b91af;">EventArgs</span></p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">if</span> (synchronizationContext == <span style="color: #0000ff;">null</span>)</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #2b91af;">ThreadPool</span>.QueueUserWorkItem((e) =&gt; raiseEventMethod((T)e), eventArgs);</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">synchronizationContext.Post((e) =&gt; raiseEventMethod((T)e), eventArgs);</p>
<p style="margin: 0px">}</p>
<p style="margin: 0px">}</p>
<p>}</p>
<p>The use of an anonymous delegate can be used for either implementation. The .NET 3.5 version uses a lambda expression just to demonstrate an alternate way of invoking the action.</p>
<p><big><big><span style="font-weight: bold">Sample UI and Worker Classes</span></big></big></p>
<p>The sample UI and worker classes are very simple examples that will be the reference code for the techniques that follow. The UI code remains virtually unchanged throughout every technique which is ideal since it should not be concerned with threading:</p>
<p><span style="color: #ff0000;">These classes do not work together as is, they need a ThreadBarrier.</span></p>
<p><span style="font-weight: bold">Sample Worker Class</span></p>
<p><!-- {\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;\red0\green0\blue255;\red43\green145\blue175;\red0\green128\blue0;}??\fs16     \cf3 public\cf0  \cf3 class\cf0  \cf4 WeatherChecker\par ??\cf0     \{\par ??        \cf3 public\cf0  \cf3 event\cf0  \cf4 EventHandler\cf0 &amp;lt;\cf4 WeatherEventArgs\cf0 &amp;gt; TemperatureChanged;\par ??        \cf3 public\cf0  \cf3 event\cf0  \cf4 EventHandler\cf0 &amp;lt;\cf4 WeatherEventArgs\cf0 &amp;gt; HumidityChanged;\par ??        \cf3 public\cf0  \cf3 event\cf0  \cf4 EventHandler\cf0 &amp;lt;\cf4 WeatherEventArgs\cf0 &amp;gt; WindChanged;\par ??        \cf3 public\cf0  \cf3 event\cf0  \cf4 EventHandler\cf0  Stopped;\par ??\par ??        \cf3 private\cf0  \cf3 bool\cf0  _isStopRequested;\par ??        \cf3 private\cf0  \cf4 Random\cf0  _random;\par ??\par ??        \cf3 public\cf0  WeatherChecker()\par ??        \{\par ??            \cf3 this\cf0 ._isStopRequested = \cf3 false\cf0 ;\par ??\par ??            \cf5 //used for generating random weather information\par ??\cf0             \cf3 this\cf0 ._random = \cf3 new\cf0  \cf4 Random\cf0 ((\cf3 int\cf0 )\cf4 DateTime\cf0 .Now.Ticks);\par ??        \}\par ??\par ??        \cf3 public\cf0  \cf3 void\cf0  Start()\par ??        \{\par ??            \cf4 Thread\cf0  thread = \cf3 new\cf0  \cf4 Thread\cf0 (\cf3 new\cf0  \cf4 ThreadStart\cf0 (CheckWeather));\par ??            thread.IsBackground = \cf3 true\cf0 ; \cf5 //prevents thread from keeping app alive when app is closed\par ??\cf0             thread.Start();\par ??        \}\par ??\par ??        \cf3 private\cf0  \cf3 void\cf0  CheckWeather()\par ??        \{\par ??            \cf3 while\cf0  (\cf3 this\cf0 ._isStopRequested == \cf3 false\cf0 )\par ??            \{\par ??                OnTemperatureChanged(\cf3 new\cf0  \cf4 WeatherEventArgs\cf0 (Rand(30f)));\par ??                OnWindChanged(\cf3 new\cf0  \cf4 WeatherEventArgs\cf0 (Rand(15f)));\par ??                OnHumidityChanged(\cf3 new\cf0  \cf4 WeatherEventArgs\cf0 (Rand(100f)));\par ??\par ??                \cf5 //Updates roughly 4 times per second\par ??\cf0                 \cf4 Thread\cf0 .Sleep(250);\par ??            \}\par ??\par ??            OnStopped(\cf4 EventArgs\cf0 .Empty);\par ??        \}\par ??\par ??        \cf3 public\cf0  \cf3 void\cf0  RequestStop()\par ??        \{\par ??            \cf3 this\cf0 ._isStopRequested = \cf3 true\cf0 ;\par ??        \}\par ??\par ??        \cf3 private\cf0  \cf3 float\cf0  Rand(\cf3 float\cf0  max)\par ??        \{\par ??            \cf3 return\cf0  (\cf3 float\cf0 )\cf3 this\cf0 ._random.NextDouble() * max;\par ??        \}\par ??\par ??        \cf3 protected\cf0  \cf3 virtual\cf0  \cf3 void\cf0  OnTemperatureChanged(\cf4 WeatherEventArgs\cf0  e)\par ??        \{\par ??            \cf3 if\cf0  (\cf3 this\cf0 .TemperatureChanged != \cf3 null\cf0 )\par ??            \{\par ??                \cf3 this\cf0 .TemperatureChanged(\cf3 this\cf0 , e);\par ??            \}\par ??        \}\par ??        \cf3 protected\cf0  \cf3 virtual\cf0  \cf3 void\cf0  OnHumidityChanged(\cf4 WeatherEventArgs\cf0  e)\par ??        \{\par ??            \cf3 if\cf0  (\cf3 this\cf0 .HumidityChanged != \cf3 null\cf0 )\par ??            \{\par ??                \cf3 this\cf0 .HumidityChanged(\cf3 this\cf0 , e);\par ??            \}\par ??        \}\par ??        \cf3 protected\cf0  \cf3 virtual\cf0  \cf3 void\cf0  OnWindChanged(\cf4 WeatherEventArgs\cf0  e)\par ??        \{\par ??            \cf3 if\cf0  (\cf3 this\cf0 .WindChanged != \cf3 null\cf0 )\par ??            \{\par ??                \cf3 this\cf0 .WindChanged(\cf3 this\cf0 , e);\par ??            \}\par ??        \}\par ??        \cf3 protected\cf0  \cf3 virtual\cf0  \cf3 void\cf0  OnStopped(\cf4 EventArgs\cf0  e)\par ??        \{\par ??            \cf3 if\cf0  (\cf3 this\cf0 .Stopped != \cf3 null\cf0 )\par ??            \{\par ??                \cf3 this\cf0 .Stopped(\cf3 this\cf0 , e);\par ??            \}\par ??        \}\par ??    \}} --></p>
<p style="margin: 0px"><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span> <span style="color: #2b91af;">WeatherChecker</span></p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">event</span> <span style="color: #2b91af;">EventHandler</span>&lt;<span style="color: #2b91af;">WeatherEventArgs</span>&gt; TemperatureChanged;</p>
<p style="margin: 0px"><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">event</span> <span style="color: #2b91af;">EventHandler</span>&lt;<span style="color: #2b91af;">WeatherEventArgs</span>&gt; HumidityChanged;</p>
<p style="margin: 0px"><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">event</span> <span style="color: #2b91af;">EventHandler</span>&lt;<span style="color: #2b91af;">WeatherEventArgs</span>&gt; WindChanged;</p>
<p style="margin: 0px"><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">event</span> <span style="color: #2b91af;">EventHandler</span> Stopped;</p>
<p style="margin: 0px"> </p>
<p style="margin: 0px"><span style="color: #0000ff;">private</span> <span style="color: #0000ff;">bool</span> _isStopRequested;</p>
<p style="margin: 0px"><span style="color: #0000ff;">private</span> <span style="color: #2b91af;">Random</span> _random;</p>
<p style="margin: 0px"> </p>
<p style="margin: 0px"><span style="color: #0000ff;">public</span> WeatherChecker()</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>._isStopRequested = <span style="color: #0000ff;">false</span>;</p>
<p style="margin: 0px"> </p>
<p style="margin: 0px"><span style="color: #008000;">//used for generating random weather information</span></p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>._random = <span style="color: #0000ff;">new</span> <span style="color: #2b91af;">Random</span>((<span style="color: #0000ff;">int</span>)<span style="color: #2b91af;">DateTime</span>.Now.Ticks);</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> Start()</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #2b91af;">Thread</span> thread = <span style="color: #0000ff;">new</span> <span style="color: #2b91af;">Thread</span>(<span style="color: #0000ff;">new</span> <span style="color: #2b91af;">ThreadStart</span>(CheckWeather));</p>
<p style="margin: 0px">thread.IsBackground = <span style="color: #0000ff;">true</span>; <span style="color: #008000;">//prevents thread from keeping app alive when app is closed</span></p>
<p style="margin: 0px">thread.Start();</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> CheckWeather()</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">while</span> (<span style="color: #0000ff;">this</span>._isStopRequested == <span style="color: #0000ff;">false</span>)</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px">OnTemperatureChanged(<span style="color: #0000ff;">new</span> <span style="color: #2b91af;">WeatherEventArgs</span>(Rand(30f)));</p>
<p style="margin: 0px">OnWindChanged(<span style="color: #0000ff;">new</span> <span style="color: #2b91af;">WeatherEventArgs</span>(Rand(15f)));</p>
<p style="margin: 0px">OnHumidityChanged(<span style="color: #0000ff;">new</span> <span style="color: #2b91af;">WeatherEventArgs</span>(Rand(100f)));</p>
<p style="margin: 0px"> </p>
<p style="margin: 0px"><span style="color: #008000;">//Updates roughly 4 times per second</span></p>
<p style="margin: 0px"><span style="color: #2b91af;">Thread</span>.Sleep(250);</p>
<p style="margin: 0px">}</p>
<p style="margin: 0px"> </p>
<p style="margin: 0px">OnStopped(<span style="color: #2b91af;">EventArgs</span>.Empty);</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> RequestStop()</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>._isStopRequested = <span style="color: #0000ff;">true</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;">float</span> Rand(<span style="color: #0000ff;">float</span> max)</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">return</span> (<span style="color: #0000ff;">float</span>)<span style="color: #0000ff;">this</span>._random.NextDouble() * max;</p>
<p style="margin: 0px">}</p>
<p style="margin: 0px"> </p>
<p style="margin: 0px"><span style="color: #0000ff;">protected</span> <span style="color: #0000ff;">virtual</span> <span style="color: #0000ff;">void</span> OnTemperatureChanged(<span style="color: #2b91af;">WeatherEventArgs</span> e)</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">if</span> (<span style="color: #0000ff;">this</span>.TemperatureChanged != <span style="color: #0000ff;">null</span>)</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>.TemperatureChanged(<span style="color: #0000ff;">this</span>, e);</p>
<p style="margin: 0px">}</p>
<p style="margin: 0px">}</p>
<p style="margin: 0px"><span style="color: #0000ff;">protected</span> <span style="color: #0000ff;">virtual</span> <span style="color: #0000ff;">void</span> OnHumidityChanged(<span style="color: #2b91af;">WeatherEventArgs</span> e)</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">if</span> (<span style="color: #0000ff;">this</span>.HumidityChanged != <span style="color: #0000ff;">null</span>)</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>.HumidityChanged(<span style="color: #0000ff;">this</span>, e);</p>
<p style="margin: 0px">}</p>
<p style="margin: 0px">}</p>
<p style="margin: 0px"><span style="color: #0000ff;">protected</span> <span style="color: #0000ff;">virtual</span> <span style="color: #0000ff;">void</span> OnWindChanged(<span style="color: #2b91af;">WeatherEventArgs</span> e)</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">if</span> (<span style="color: #0000ff;">this</span>.WindChanged != <span style="color: #0000ff;">null</span>)</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>.WindChanged(<span style="color: #0000ff;">this</span>, e);</p>
<p style="margin: 0px">}</p>
<p style="margin: 0px">}</p>
<p style="margin: 0px"><span style="color: #0000ff;">protected</span> <span style="color: #0000ff;">virtual</span> <span style="color: #0000ff;">void</span> OnStopped(<span style="color: #2b91af;">EventArgs</span> e)</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">if</span> (<span style="color: #0000ff;">this</span>.Stopped != <span style="color: #0000ff;">null</span>)</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>.Stopped(<span style="color: #0000ff;">this</span>, e);</p>
<p style="margin: 0px">}</p>
<p style="margin: 0px">}</p>
<p style="margin: 0px">}</p>
<p><span style="font-weight: bold">Sample UI Class</span></p>
<p><!-- {\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;\red0\green0\blue255;\red43\green145\blue175;\red163\green21\blue21;}??\fs16     \cf3 public\cf0  \cf3 partial\cf0  \cf3 class\cf0  \cf4 Form1\cf0  : \cf4 Form\par ??\cf0     \{\par ??        \cf3 private\cf0  \cf4 ThreadBarrierWeatherChecker\cf0  _weatherChecker;\par ??\par ??        \cf3 public\cf0  Form1()\par ??        \{\par ??            InitializeComponent();\par ??        \}\par ??\par ??        \cf3 private\cf0  \cf3 void\cf0  buttonStart_Click(\cf3 object\cf0  sender, \cf4 EventArgs\cf0  e)\par ??        \{\par ??            \cf3 this\cf0 .buttonStart.Enabled = \cf3 false\cf0 ;\par ??            \cf3 this\cf0 .buttonStop.Enabled = \cf3 true\cf0 ;\par ??\par ??            \cf3 this\cf0 ._weatherChecker = \cf3 new\cf0  \cf4 ThreadBarrierWeatherChecker\cf0 ();\par ??            \cf3 this\cf0 ._weatherChecker.TemperatureChanged += \cf3 new\cf0  \cf4 EventHandler\cf0 &amp;lt;\cf4 WeatherEventArgs\cf0 &amp;gt;(_weatherChecker_TemperatureChanged);\par ??            \cf3 this\cf0 ._weatherChecker.HumidityChanged += \cf3 new\cf0  \cf4 EventHandler\cf0 &amp;lt;\cf4 WeatherEventArgs\cf0 &amp;gt;(_weatherChecker_HumidityChanged);\par ??            \cf3 this\cf0 ._weatherChecker.WindChanged += \cf3 new\cf0  \cf4 EventHandler\cf0 &amp;lt;\cf4 WeatherEventArgs\cf0 &amp;gt;(_weatherChecker_WindChanged);\par ??            \cf3 this\cf0 ._weatherChecker.Stopped += \cf3 new\cf0  \cf4 EventHandler\cf0 (_weatherChecker_Stopped);\par ??\par ??            \cf3 this\cf0 ._weatherChecker.Start();\par ??        \}\par ??\par ??        \cf3 private\cf0  \cf3 void\cf0  buttonStop_Click(\cf3 object\cf0  sender, \cf4 EventArgs\cf0  e)\par ??        \{\par ??            \cf3 this\cf0 ._weatherChecker.RequestStop();\par ??        \}\par ??\par ??        \cf3 void\cf0  _weatherChecker_TemperatureChanged(\cf3 object\cf0  sender, \cf4 WeatherEventArgs\cf0  e)\par ??        \{\par ??            \cf3 this\cf0 .labelTemperature.Text = \cf4 String\cf0 .Format(\cf5 "\{0:F1\} C"\cf0 , e.Value);\par ??        \}\par ??\par ??        \cf3 void\cf0  _weatherChecker_HumidityChanged(\cf3 object\cf0  sender, \cf4 WeatherEventArgs\cf0  e)\par ??        \{\par ??            \cf3 this\cf0 .labelHumidity.Text = \cf4 String\cf0 .Format(\cf5 "\{0:F0\}%"\cf0 , e.Value);\par ??        \}\par ??\par ??        \cf3 void\cf0  _weatherChecker_WindChanged(\cf3 object\cf0  sender, \cf4 WeatherEventArgs\cf0  e)\par ??        \{\par ??            \cf3 this\cf0 .labelWind.Text = \cf4 String\cf0 .Format(\cf5 "\{0:F0\} mph"\cf0 , e.Value);\par ??        \}\par ??\par ??        \cf3 void\cf0  _weatherChecker_Stopped(\cf3 object\cf0  sender, \cf4 EventArgs\cf0  e)\par ??        \{\par ??            \cf3 this\cf0 .buttonStop.Enabled = \cf3 false\cf0 ;\par ??            \cf3 this\cf0 .buttonStart.Enabled = \cf3 true\cf0 ;\par ??\par ??            \cf3 this\cf0 ._weatherChecker = \cf3 null\cf0 ;\par ??        \}\par ??    \}} --></p>
<p style="margin: 0px"><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">partial</span> <span style="color: #0000ff;">class</span> <span style="color: #2b91af;">Form1</span> : <span style="color: #2b91af;">Form</span></p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">private</span> <span style="color: #2b91af;">WeatherChecker</span> _weatherChecker;</p>
<p style="margin: 0px"> </p>
<p style="margin: 0px"><span style="color: #0000ff;">public</span> Form1()</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px">InitializeComponent();</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> buttonStart_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: #0000ff;">this</span>.buttonStart.Enabled = <span style="color: #0000ff;">false</span>;</p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>.buttonStop.Enabled = <span style="color: #0000ff;">true</span>;</p>
<p style="margin: 0px"> </p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>._weatherChecker = <span style="color: #0000ff;">new</span> <span style="color: #2b91af;">WeatherChecker</span>();</p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>._weatherChecker.TemperatureChanged += <span style="color: #0000ff;">new</span> <span style="color: #2b91af;">EventHandler</span>&lt;<span style="color: #2b91af;">WeatherEventArgs</span>&gt;(_weatherChecker_TemperatureChanged);</p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>._weatherChecker.HumidityChanged += <span style="color: #0000ff;">new</span> <span style="color: #2b91af;">EventHandler</span>&lt;<span style="color: #2b91af;">WeatherEventArgs</span>&gt;(_weatherChecker_HumidityChanged);</p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>._weatherChecker.WindChanged += <span style="color: #0000ff;">new</span> <span style="color: #2b91af;">EventHandler</span>&lt;<span style="color: #2b91af;">WeatherEventArgs</span>&gt;(_weatherChecker_WindChanged);</p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>._weatherChecker.Stopped += <span style="color: #0000ff;">new</span> <span style="color: #2b91af;">EventHandler</span>(_weatherChecker_Stopped);</p>
<p style="margin: 0px"> </p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>._weatherChecker.Start();</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> buttonStop_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: #0000ff;">this</span>._weatherChecker.RequestStop();</p>
<p style="margin: 0px">}</p>
<p style="margin: 0px"> </p>
<p style="margin: 0px"><span style="color: #0000ff;">void</span> _weatherChecker_TemperatureChanged(<span style="color: #0000ff;">object</span> sender, <span style="color: #2b91af;">WeatherEventArgs</span> e)</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>.labelTemperature.Text = <span style="color: #2b91af;">String</span>.Format(<span style="color: #a31515;">&#8220;{0:F1} C&#8221;</span>, e.Value);</p>
<p style="margin: 0px">}</p>
<p style="margin: 0px"> </p>
<p style="margin: 0px"><span style="color: #0000ff;">void</span> _weatherChecker_HumidityChanged(<span style="color: #0000ff;">object</span> sender, <span style="color: #2b91af;">WeatherEventArgs</span> e)</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>.labelHumidity.Text = <span style="color: #2b91af;">String</span>.Format(<span style="color: #a31515;">&#8220;{0:F0}%&#8221;</span>, e.Value);</p>
<p style="margin: 0px">}</p>
<p style="margin: 0px"> </p>
<p style="margin: 0px"><span style="color: #0000ff;">void</span> _weatherChecker_WindChanged(<span style="color: #0000ff;">object</span> sender, <span style="color: #2b91af;">WeatherEventArgs</span> e)</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>.labelWind.Text = <span style="color: #2b91af;">String</span>.Format(<span style="color: #a31515;">&#8220;{0:F0} mph&#8221;</span>, e.Value);</p>
<p style="margin: 0px">}</p>
<p style="margin: 0px"> </p>
<p style="margin: 0px"><span style="color: #0000ff;">void</span> _weatherChecker_Stopped(<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: #0000ff;">this</span>.buttonStop.Enabled = <span style="color: #0000ff;">false</span>;</p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>.buttonStart.Enabled = <span style="color: #0000ff;">true</span>;</p>
<p style="margin: 0px"> </p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>._weatherChecker = <span style="color: #0000ff;">null</span>;</p>
<p style="margin: 0px">}</p>
<p style="margin: 0px">}</p>
<p><big><big><span style="font-weight: bold">ThreadBarrier Technique #1: Subclassing an existing worker thread class</span></big></big></p>
<p>The two classes above are doing nothing special to communicate with on another. An attempt to use the two together would fail since the worker class is raising events on the worker thread which is not allowed to access controls on the UI thread. Amazingly using a ThreadBarrier in the following way causes all events from the worker class to be automatically raised on the UI thread:</p>
<p><!-- {\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;\red0\green0\blue255;\red43\green145\blue175;}??\fs16     \cf3 public\cf0  \cf3 class\cf0  \cf4 ThreadBarrierWeatherChecker\cf0  : \cf4 WeatherChecker\par ??\cf0     \{\par ??        \cf3 private\cf0  \cf4 ThreadBarrier\cf0  _threadBarrier;\par ??\par ??        \cf3 public\cf0  ThreadBarrierWeatherChecker()\par ??        \{\par ??            \cf3 this\cf0 ._threadBarrier = \cf3 new\cf0  \cf4 ThreadBarrier\cf0 ();\par ??        \}\par ??\par ??        \cf3 protected\cf0  \cf3 override\cf0  \cf3 void\cf0  OnTemperatureChanged(\cf4 WeatherEventArgs\cf0  e)\par ??        \{\par ??            \cf3 this\cf0 ._threadBarrier.Post(e, \cf3 base\cf0 .OnTemperatureChanged);\par ??        \}\par ??\par ??        \cf3 protected\cf0  \cf3 override\cf0  \cf3 void\cf0  OnWindChanged(\cf4 WeatherEventArgs\cf0  e)\par ??        \{\par ??            \cf3 this\cf0 ._threadBarrier.Post(e, \cf3 base\cf0 .OnWindChanged);\par ??        \}\par ??\par ??        \cf3 protected\cf0  \cf3 override\cf0  \cf3 void\cf0  OnHumidityChanged(\cf4 WeatherEventArgs\cf0  e)\par ??        \{\par ??            \cf3 this\cf0 ._threadBarrier.Post(e, \cf3 base\cf0 .OnHumidityChanged);\par ??        \}\par ??\par ??        \cf3 protected\cf0  \cf3 override\cf0  \cf3 void\cf0  OnStopped(\cf4 EventArgs\cf0  e)\par ??        \{\par ??            \cf3 this\cf0 ._threadBarrier.Post(e, \cf3 base\cf0 .OnStopped);\par ??        \}\par ??    \}} --></p>
<p style="font-size: 8pt; background: white 0% 50%; color: black; font-family: Courier New; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial"><!-- {\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;\red0\green0\blue255;\red43\green145\blue175;}??\fs16     \cf3 public\cf0  \cf3 class\cf0  \cf4 ThreadBarrierWeatherChecker\cf0  : \cf4 WeatherChecker\par ??\cf0     \{\par ??        \cf3 private\cf0  \cf4 ThreadBarrier\cf0  _threadBarrier;\par ??\par ??        \cf3 public\cf0  ThreadBarrierWeatherChecker()\par ??        \{\par ??            \cf3 this\cf0 ._threadBarrier = \cf3 new\cf0  \cf4 ThreadBarrier\cf0 ();\par ??        \}\par ??\par ??        \cf3 protected\cf0  \cf3 override\cf0  \cf3 void\cf0  OnTemperatureChanged(\cf4 WeatherEventArgs\cf0  e)\par ??        \{\par ??            \cf3 this\cf0 ._threadBarrier.Post(\cf3 base\cf0 .OnTemperatureChanged, e);\par ??        \}\par ??\par ??        \cf3 protected\cf0  \cf3 override\cf0  \cf3 void\cf0  OnWindChanged(\cf4 WeatherEventArgs\cf0  e)\par ??        \{\par ??            \cf3 this\cf0 ._threadBarrier.Post(\cf3 base\cf0 .OnWindChanged, e);\par ??        \}\par ??\par ??        \cf3 protected\cf0  \cf3 override\cf0  \cf3 void\cf0  OnHumidityChanged(\cf4 WeatherEventArgs\cf0  e)\par ??        \{\par ??            \cf3 this\cf0 ._threadBarrier.Post(\cf3 base\cf0 .OnHumidityChanged, e);\par ??        \}\par ??\par ??        \cf3 protected\cf0  \cf3 override\cf0  \cf3 void\cf0  OnStopped(\cf4 EventArgs\cf0  e)\par ??        \{\par ??            \cf3 this\cf0 ._threadBarrier.Post(\cf3 base\cf0 .OnStopped, e);\par ??        \}\par ??    \}} --></p>
<p style="margin: 0px"><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span> <span style="color: #2b91af;">ThreadBarrierWeatherChecker</span> : <span style="color: #2b91af;">WeatherChecker</span></p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">private</span> <span style="color: #2b91af;">ThreadBarrier</span> _threadBarrier;</p>
<p style="margin: 0px"> </p>
<p style="margin: 0px"><span style="color: #0000ff;">public</span> ThreadBarrierWeatherChecker()</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>._threadBarrier = <span style="color: #0000ff;">new</span> <span style="color: #2b91af;">ThreadBarrier</span>();</p>
<p style="margin: 0px">}</p>
<p style="margin: 0px"> </p>
<p style="margin: 0px"><span style="color: #0000ff;">protected</span> <span style="color: #0000ff;">override</span> <span style="color: #0000ff;">void</span> OnTemperatureChanged(<span style="color: #2b91af;">WeatherEventArgs</span> e)</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>._threadBarrier.Post(<span style="color: #0000ff;">base</span>.OnTemperatureChanged, e);</p>
<p style="margin: 0px">}</p>
<p style="margin: 0px"> </p>
<p style="margin: 0px"><span style="color: #0000ff;">protected</span> <span style="color: #0000ff;">override</span> <span style="color: #0000ff;">void</span> OnWindChanged(<span style="color: #2b91af;">WeatherEventArgs</span> e)</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>._threadBarrier.Post(<span style="color: #0000ff;">base</span>.OnWindChanged, e);</p>
<p style="margin: 0px">}</p>
<p style="margin: 0px"> </p>
<p style="margin: 0px"><span style="color: #0000ff;">protected</span> <span style="color: #0000ff;">override</span> <span style="color: #0000ff;">void</span> OnHumidityChanged(<span style="color: #2b91af;">WeatherEventArgs</span> e)</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>._threadBarrier.Post(<span style="color: #0000ff;">base</span>.OnHumidityChanged, e);</p>
<p style="margin: 0px">}</p>
<p style="margin: 0px"> </p>
<p style="margin: 0px"><span style="color: #0000ff;">protected</span> <span style="color: #0000ff;">override</span> <span style="color: #0000ff;">void</span> OnStopped(<span style="color: #2b91af;">EventArgs</span> e)</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>._threadBarrier.Post(<span style="color: #0000ff;">base</span>.OnStopped, e);</p>
<p style="margin: 0px">}</p>
<p style="margin: 0px">}</p>
<p>That&#8217;s it! All it took was deriving from the worker class and posting the <span style="font-style: italic">method</span> that raises the events to the UI thread. The UI class should create an instance of <span style="color: #339999;">ThreadBarrierWeatherChecker</span> rather than <span style="color: #339999;">WeatherChecker</span>. This technique is handy if you do not own or can&#8217;t modify the code to the worker class.</p>
<p><big><big><span style="font-weight: bold">ThreadBarrier Technique #2: Using extension methods on a SynchronizationContext</span></big></big><br />
<span style="font-family: Courier New;"><br />
</span>This technique requires the developer to not only have access to the WeatherChecker code, but also capture the UI&#8217;s SynchronizationContext in the WeatherChecker&#8217;s constructor:</p>
<p><!-- {\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;\red0\green0\blue255;\red43\green145\blue175;\red0\green128\blue0;}??\fs16         \cf3 private\cf0  \cf4 SynchronizationContext\cf0  _synchronizationContext;\par ??\par ??        \cf3 private\cf0  \cf3 bool\cf0  _isStopRequested;\par ??        \cf3 private\cf0  \cf4 Random\cf0  _random;\par ??\par ??        \cf3 public\cf0  WeatherChecker()\par ??        \{\par ??            \cf3 this\cf0 ._synchronizationContext = \cf4 AsyncOperationManager\cf0 .SynchronizationContext;\par ??\par ??            \cf3 this\cf0 ._isStopRequested = \cf3 false\cf0 ;\par ??\par ??            \cf5 //used for generating random weather information\par ??\cf0             \cf3 this\cf0 ._random = \cf3 new\cf0  \cf4 Random\cf0 ((\cf3 int\cf0 )\cf4 DateTime\cf0 .Now.Ticks);\par ??        \}} --></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> WeatherChecker()</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>._synchronizationContext = <span style="color: #2b91af;">AsyncOperationManager</span>.SynchronizationContext;</p>
<p style="margin: 0px">&#8230;</p>
<p style="margin: 0px">}</p>
<p>Raising events now uses the _synchronizationContext field and the ThreadBarrier extension method:</p>
<p><!-- {\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;\red0\green0\blue255;\red43\green145\blue175;}??\fs16                 \cf3 this\cf0 ._synchronizationContext.Post(OnTemperatureChanged, \cf3 new\cf0  \cf4 WeatherEventArgs\cf0 (Rand(30f)));\par ??                \cf3 this\cf0 ._synchronizationContext.Post(OnWindChanged, \cf3 new\cf0  \cf4 WeatherEventArgs\cf0 (Rand(15f)));\par ??                \cf3 this\cf0 ._synchronizationContext.Post(OnHumidityChanged, \cf3 new\cf0  \cf4 WeatherEventArgs\cf0 (Rand(100f)));} --></p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>._synchronizationContext.Post(OnTemperatureChanged, <span style="color: #0000ff;">new</span> <span style="color: #2b91af;">WeatherEventArgs</span>(Rand(30f)));</p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>._synchronizationContext.Post(OnWindChanged, <span style="color: #0000ff;">new</span> <span style="color: #2b91af;">WeatherEventArgs</span>(Rand(15f)));</p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>._synchronizationContext.Post(OnHumidityChanged, <span style="color: #0000ff;">new</span> <span style="color: #2b91af;">WeatherEventArgs</span>(Rand(100f)));</p>
<p><big><big><span style="font-weight: bold">ThreadBarrier Technique #3: Deriving from a ThreadBarrier</span></big></big></p>
<p>Again if the developer is in full control of the worker class, all that it takes is deriving from a ThreadBarrier to inherit the method that provides the posting to the UI thread:</p>
<p><!-- {\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;\red0\green0\blue255;\red43\green145\blue175;}??\fs16     \cf3 public\cf0  \cf3 class\cf0  \cf4 WeatherChecker\cf0  : \cf4 ThreadBarrier\par ??} --></p>
<p style="margin: 0px"><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span> <span style="color: #2b91af;">WeatherChecker</span> : <span style="color: #2b91af;">ThreadBarrier</span></p>
<p>Raising the events is now a matter of calling the Post method in the base ThreadBarrier class:</p>
<p><!-- {\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;\red0\green0\blue255;\red43\green145\blue175;}??\fs16                 Post(\cf3 new\cf0  \cf4 WeatherEventArgs\cf0 (Rand(30f)), OnTemperatureChanged);\par ??                Post(\cf3 new\cf0  \cf4 WeatherEventArgs\cf0 (Rand(15f)), OnWindChanged);\par ??                Post(\cf3 new\cf0  \cf4 WeatherEventArgs\cf0 (Rand(100f)), OnHumidityChanged);} --><!-- {\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;\red0\green0\blue255;\red43\green145\blue175;}??\fs16                 Post(OnTemperatureChanged, \cf3 new\cf0  \cf4 WeatherEventArgs\cf0 (Rand(30f)));\par ??                Post(OnWindChanged, \cf3 new\cf0  \cf4 WeatherEventArgs\cf0 (Rand(15f)));\par ??                Post(OnHumidityChanged, \cf3 new\cf0  \cf4 WeatherEventArgs\cf0 (Rand(100f)));} --></p>
<p style="margin: 0px">Post(OnTemperatureChanged, <span style="color: #0000ff;">new</span> <span style="color: #2b91af;">WeatherEventArgs</span>(Rand(30f)));</p>
<p style="margin: 0px">Post(OnWindChanged, <span style="color: #0000ff;">new</span> <span style="color: #2b91af;">WeatherEventArgs</span>(Rand(15f)));</p>
<p style="margin: 0px">Post(OnHumidityChanged, <span style="color: #0000ff;">new</span> <span style="color: #2b91af;">WeatherEventArgs</span>(Rand(100f)));</p>
<p>In order for the ThreadBarrier to work the WeatherChecker class needs to be created on the UI thread so the base ThreadBarrier class can capture the UI&#8217;s SynchronizationContext.</p>
<p><big><big><span style="font-weight: bold">ThreadBarrier Technique #4: Creating an instance of a ThreadBarrier</span></big></big></p>
<p>If deriving from a ThreadBarrier is not an option, just creating an instance of a ThreadBarrier will work as well. This implementation is similar to the extension method sample, but the ThreadBarrier instance will hide the capturing and storing of the SynchronizationContext. This technique also requires the WeatherChecker to be created on the UI thread.</p>
<p><!-- {\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;\red0\green0\blue255;\red43\green145\blue175;\red0\green128\blue0;}??\fs16         \cf3 private\cf0  \cf4 ThreadBarrier\cf0  _threadBarrier;\par ??\par ??        \cf3 private\cf0  \cf3 bool\cf0  _isStopRequested;\par ??        \cf3 private\cf0  \cf4 Random\cf0  _random;\par ??\par ??        \cf3 public\cf0  WeatherChecker()\par ??        \{\par ??            \cf3 this\cf0 ._threadBarrier = \cf3 new\cf0  \cf4 ThreadBarrier\cf0 ();\par ??\par ??            \cf3 this\cf0 ._isStopRequested = \cf3 false\cf0 ;\par ??\par ??            \cf5 //used for generating random weather information\par ??\cf0             \cf3 this\cf0 ._random = \cf3 new\cf0  \cf4 Random\cf0 ((\cf3 int\cf0 )\cf4 DateTime\cf0 .Now.Ticks);\par ??        \}} --></p>
<p style="margin: 0px"><span style="color: #0000ff;">private</span> <span style="color: #2b91af;">ThreadBarrier</span> _threadBarrier;</p>
<p style="margin: 0px"> </p>
<p style="margin: 0px"><span style="color: #0000ff;">public</span> WeatherChecker()</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>._threadBarrier = <span style="color: #0000ff;">new</span> <span style="color: #2b91af;">ThreadBarrier</span>();</p>
<p style="margin: 0px">&#8230;</p>
<p style="margin: 0px">}</p>
<p><!-- {\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;\red0\green0\blue255;\red43\green145\blue175;}??\fs16                 \cf3 this\cf0 ._threadBarrier.Post(\cf3 new\cf0  \cf4 WeatherEventArgs\cf0 (Rand(30f)), OnTemperatureChanged);\par ??                \cf3 this\cf0 ._threadBarrier.Post(\cf3 new\cf0  \cf4 WeatherEventArgs\cf0 (Rand(15f)), OnWindChanged);\par ??                \cf3 this\cf0 ._threadBarrier.Post(\cf3 new\cf0  \cf4 WeatherEventArgs\cf0 (Rand(100f)), OnHumidityChanged);} --><!-- {\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;\red0\green0\blue255;\red43\green145\blue175;}??\fs16                 \cf3 this\cf0 ._threadBarrier.Post(OnTemperatureChanged, \cf3 new\cf0  \cf4 WeatherEventArgs\cf0 (Rand(30f)));\par ??                \cf3 this\cf0 ._threadBarrier.Post(OnWindChanged, \cf3 new\cf0  \cf4 WeatherEventArgs\cf0 (Rand(15f)));\par ??                \cf3 this\cf0 ._threadBarrier.Post(OnHumidityChanged, \cf3 new\cf0  \cf4 WeatherEventArgs\cf0 (Rand(100f)));} --></p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>._threadBarrier.Post(OnTemperatureChanged, <span style="color: #0000ff;">new</span> <span style="color: #2b91af;">WeatherEventArgs</span>(Rand(30f)));</p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>._threadBarrier.Post(OnWindChanged, <span style="color: #0000ff;">new</span> <span style="color: #2b91af;">WeatherEventArgs</span>(Rand(15f)));</p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>._threadBarrier.Post(OnHumidityChanged, <span style="color: #0000ff;">new</span> <span style="color: #2b91af;">WeatherEventArgs</span>(Rand(100f)));</p>
<p><big><big><span style="font-weight: bold">ThreadBarrier Technique #5: Creating an adapter class to propagate events</span></big></big></p>
<p>This technique should be a last resort for the scenario where you can&#8217;t derive from the worker class and you are unable to modify its code. Since an extra set of events need to be created and subscribed, it can be dangerous and lead to memory leaks if the handlers are not properly removed.</p>
<p><strong>Adapter Class</strong> (extra events removed for compactness)<br />
<!-- {\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;\red0\green0\blue255;\red43\green145\blue175;}??\fs16     \cf3 public\cf0  \cf3 class\cf0  \cf4 ThreadBarrierWeatherChecker\cf0  : \cf4 ThreadBarrier\par ??\cf0     \{\par ??        \cf3 public\cf0  \cf3 event\cf0  \cf4 EventHandler\cf0 &amp;lt;\cf4 WeatherEventArgs\cf0 &amp;gt; TemperatureChanged;\par ??        \cf3 public\cf0  \cf3 event\cf0  \cf4 EventHandler\cf0 &amp;lt;\cf4 WeatherEventArgs\cf0 &amp;gt; HumidityChanged;\par ??        \cf3 public\cf0  \cf3 event\cf0  \cf4 EventHandler\cf0 &amp;lt;\cf4 WeatherEventArgs\cf0 &amp;gt; WindChanged;\par ??        \cf3 public\cf0  \cf3 event\cf0  \cf4 EventHandler\cf0  Stopped;\par ??\par ??        \cf3 private\cf0  \cf4 WeatherChecker\cf0  _weatherChecker;\par ??\par ??        \cf3 public\cf0  ThreadBarrierWeatherChecker()\par ??        \{\par ??        \}\par ??\par ??        \cf3 public\cf0  \cf3 void\cf0  Attach(\cf4 WeatherChecker\cf0  weatherChecker)\par ??        \{\par ??            \cf3 this\cf0 ._weatherChecker = weatherChecker;\par ??            \cf3 this\cf0 ._weatherChecker.TemperatureChanged += \cf3 new\cf0  \cf4 EventHandler\cf0 &amp;lt;\cf4 WeatherEventArgs\cf0 &amp;gt;(_weatherChecker_TemperatureChanged);\par ??            \cf3 this\cf0 ._weatherChecker.WindChanged += \cf3 new\cf0  \cf4 EventHandler\cf0 &amp;lt;\cf4 WeatherEventArgs\cf0 &amp;gt;(_weatherChecker_WindChanged);\par ??            \cf3 this\cf0 ._weatherChecker.HumidityChanged += \cf3 new\cf0  \cf4 EventHandler\cf0 &amp;lt;\cf4 WeatherEventArgs\cf0 &amp;gt;(_weatherChecker_HumidityChanged);\par ??            \cf3 this\cf0 ._weatherChecker.Stopped += \cf3 new\cf0  \cf4 EventHandler\cf0 (_weatherChecker_Stopped);\par ??        \}\par ??\par ??        \cf3 public\cf0  \cf3 void\cf0  Detach()\par ??        \{\par ??            \cf3 this\cf0 ._weatherChecker.TemperatureChanged -= \cf3 new\cf0  \cf4 EventHandler\cf0 &amp;lt;\cf4 WeatherEventArgs\cf0 &amp;gt;(_weatherChecker_TemperatureChanged);\par ??            \cf3 this\cf0 ._weatherChecker.WindChanged -= \cf3 new\cf0  \cf4 EventHandler\cf0 &amp;lt;\cf4 WeatherEventArgs\cf0 &amp;gt;(_weatherChecker_WindChanged);\par ??            \cf3 this\cf0 ._weatherChecker.HumidityChanged -= \cf3 new\cf0  \cf4 EventHandler\cf0 &amp;lt;\cf4 WeatherEventArgs\cf0 &amp;gt;(_weatherChecker_HumidityChanged);\par ??            \cf3 this\cf0 ._weatherChecker.Stopped -= \cf3 new\cf0  \cf4 EventHandler\cf0 (_weatherChecker_Stopped);\par ??            \cf3 this\cf0 ._weatherChecker = \cf3 null\cf0 ;\par ??        \}\par ??\par ??        \cf3 void\cf0  _weatherChecker_TemperatureChanged(\cf3 object\cf0  sender, \cf4 WeatherEventArgs\cf0  e)\par ??        \{\par ??            Post(OnTemperatureChanged, e);\par ??        \}\par ??\par ??        \cf3 void\cf0  _weatherChecker_WindChanged(\cf3 object\cf0  sender, \cf4 WeatherEventArgs\cf0  e)\par ??        \{\par ??            Post(OnWindChanged, e);\par ??        \}\par ??\par ??        \cf3 void\cf0  _weatherChecker_HumidityChanged(\cf3 object\cf0  sender, \cf4 WeatherEventArgs\cf0  e)\par ??        \{\par ??            Post(OnHumidityChanged, e);\par ??        \}\par ??\par ??        \cf3 void\cf0  _weatherChecker_Stopped(\cf3 object\cf0  sender, \cf4 EventArgs\cf0  e)\par ??        \{\par ??            Post(OnStopped, e);\par ??        \}\par ??\par ??        \cf3 protected\cf0  \cf3 virtual\cf0  \cf3 void\cf0  OnTemperatureChanged(\cf4 WeatherEventArgs\cf0  e)\par ??        \{\par ??            \cf3 if\cf0  (\cf3 this\cf0 .TemperatureChanged != \cf3 null\cf0 )\par ??            \{\par ??                \cf3 this\cf0 .TemperatureChanged(\cf3 this\cf0 , e);\par ??            \}\par ??        \}\par ??        \cf3 protected\cf0  \cf3 virtual\cf0  \cf3 void\cf0  OnHumidityChanged(\cf4 WeatherEventArgs\cf0  e)\par ??        \{\par ??            \cf3 if\cf0  (\cf3 this\cf0 .HumidityChanged != \cf3 null\cf0 )\par ??            \{\par ??                \cf3 this\cf0 .HumidityChanged(\cf3 this\cf0 , e);\par ??            \}\par ??        \}\par ??        \cf3 protected\cf0  \cf3 virtual\cf0  \cf3 void\cf0  OnWindChanged(\cf4 WeatherEventArgs\cf0  e)\par ??        \{\par ??            \cf3 if\cf0  (\cf3 this\cf0 .WindChanged != \cf3 null\cf0 )\par ??            \{\par ??                \cf3 this\cf0 .WindChanged(\cf3 this\cf0 , e);\par ??            \}\par ??        \}\par ??        \cf3 protected\cf0  \cf3 virtual\cf0  \cf3 void\cf0  OnStopped(\cf4 EventArgs\cf0  e)\par ??        \{\par ??            \cf3 if\cf0  (\cf3 this\cf0 .Stopped != \cf3 null\cf0 )\par ??            \{\par ??                \cf3 this\cf0 .Stopped(\cf3 this\cf0 , e);\par ??            \}\par ??        \}\par ??    \}} --></p>
<p style="margin: 0px"><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span> <span style="color: #2b91af;">ThreadBarrierWeatherChecker</span> : <span style="color: #2b91af;">ThreadBarrier</span></p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">event</span> <span style="color: #2b91af;">EventHandler</span>&lt;<span style="color: #2b91af;">WeatherEventArgs</span>&gt; TemperatureChanged;</p>
<p style="margin: 0px">&#8230;</p>
<p style="margin: 0px"> </p>
<p style="margin: 0px"><span style="color: #0000ff;">private</span> <span style="color: #2b91af;">WeatherChecker</span> _weatherChecker;</p>
<p style="margin: 0px"> </p>
<p style="margin: 0px"><span style="color: #0000ff;">public</span> ThreadBarrierWeatherChecker()</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> Attach(<span style="color: #2b91af;">WeatherChecker</span> weatherChecker)</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>._weatherChecker = weatherChecker;</p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>._weatherChecker.TemperatureChanged += <span style="color: #0000ff;">new</span> <span style="color: #2b91af;">EventHandler</span>&lt;<span style="color: #2b91af;">WeatherEventArgs</span>&gt;(_weatherChecker_TemperatureChanged);</p>
<p>&#8230;</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> Detach()</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>._weatherChecker.TemperatureChanged -= <span style="color: #0000ff;">new</span> <span style="color: #2b91af;">EventHandler</span>&lt;<span style="color: #2b91af;">WeatherEventArgs</span>&gt;(_weatherChecker_TemperatureChanged);</p>
<p style="margin: 0px">&#8230;</p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>._weatherChecker = <span style="color: #0000ff;">null</span>;</p>
<p style="margin: 0px">}</p>
<p style="margin: 0px"> </p>
<p style="margin: 0px"><span style="color: #0000ff;">void</span> _weatherChecker_TemperatureChanged(<span style="color: #0000ff;">object</span> sender, <span style="color: #2b91af;">WeatherEventArgs</span> e)</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px">Post(OnTemperatureChanged, e);</p>
<p style="margin: 0px">}</p>
<p style="margin: 0px"> </p>
<p style="margin: 0px"><span style="color: #0000ff;">protected</span> <span style="color: #0000ff;">virtual</span> <span style="color: #0000ff;">void</span> OnTemperatureChanged(<span style="color: #2b91af;">WeatherEventArgs</span> e)</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">if</span> (<span style="color: #0000ff;">this</span>.TemperatureChanged != <span style="color: #0000ff;">null</span>)</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>.TemperatureChanged(<span style="color: #0000ff;">this</span>, e);</p>
<p style="margin: 0px">}</p>
<p style="margin: 0px">}</p>
<p style="margin: 0px">}</p>
<p>The adapter class needs to provide a way to attach and detach to an already existing WeatherChecker instance. If the instance is not detached, it will result in a memory leak (the adapter class will be kept alive).</p>
<p><big><big><span style="font-weight: bold">The Original ThreadBarrier Implementation Flaw</span></big></big></p>
<p>The first implementation of the ThreadBarrier used the event as a parameter:</p>
<p><!-- {\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;\red0\green0\blue255;\red43\green145\blue175;\red0\green128\blue0;}??\fs16         \cf3 protected\cf0  \cf3 void\cf0  PostEvent&amp;lt;T&amp;gt;(\cf4 EventHandler\cf0 &amp;lt;T&amp;gt; eventHandler, \cf3 object\cf0  sender, T eventArgs)\par ??            \cf3 where\cf0  T : \cf4 EventArgs\par ??\cf0         \{\par ??            \cf5 //do not raise the event if none was provided\par ??\cf0             \cf3 if\cf0  (eventHandler == \cf3 null\cf0 )\par ??            \{\par ??                \cf3 return\cf0 ;\par ??            \}\par ??\par ??            \cf3 this\cf0 ._synchronizationContext.Post(\cf3 delegate\cf0  \{ eventHandler(\cf3 this\cf0 , eventArgs); \}, \cf3 null\cf0 );\par ??        \}\par ??} --></p>
<p style="margin: 0px"><span style="color: #0000ff;">protected</span> <span style="color: #0000ff;">void</span> PostEvent&lt;T&gt;(<span style="color: #2b91af;">EventHandler</span>&lt;T&gt; eventHandler, <span style="color: #0000ff;">object</span> sender, T eventArgs)</p>
<p style="margin: 0px"><span style="color: #0000ff;">where</span> T : <span style="color: #2b91af;">EventArgs</span></p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #008000;">//do not raise the event if none was provided</span></p>
<p style="margin: 0px"><span style="color: #0000ff;">if</span> (eventHandler == <span style="color: #0000ff;">null</span>)</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">return</span>;</p>
<p style="margin: 0px">}</p>
<p style="margin: 0px"> </p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>._synchronizationContext.Post(<span style="color: #0000ff;">delegate</span> { eventHandler(<span style="color: #0000ff;">this</span>, eventArgs); }, <span style="color: #0000ff;">null</span>);</p>
<p style="margin: 0px">}</p>
<p>The problem with this implementation is that the event handler delegate is copied when passed to the method. During execution of this method (which occurs on the worker thread) a UI thread could remove the original handler and dispose of the UI control. Since the method&#8217;s copy of the delegate will still get posted to the UI thread, the handler will be executed in the control&#8217;s code even though the control was already disposed. In other words, if the worker class is being used by multiple windows or controls that are opening and closing it could lead to this problem. See Problem #2 in the <a href="http://blog.quantumbitdesigns.com/2008/07/22/events-and-threads/">Events and Threads</a> post.</p>
<p><big><big><span style="font-weight: bold">ThreadBarrier FAQ</span></big></big></p>
<p><span style="font-weight: bold">Q</span>: <span style="font-style: italic">Why not just use AsynchOperationManager.SynchronizationContext in the base class for each method post?</span><br />
<span style="font-weight: bold">A</span>: Since the methods are originally called on the worker thread, it means the call to the AsynchOperationManager.SynchronizationContext static property will be made from the worker thread. It will thus return an &#8216;empty&#8217; SynchronizationContext. The call to the static property must be made on the UI and the SynchronizationContext must be &#8217;saved&#8217; so the worker can use it.</p>
<p><span style="font-weight: bold">Q</span>: <span style="font-style: italic">Why not just use SynchronizationContext.Current?</span><br />
<span style="font-weight: bold">A</span>: The static SynchronizationContext.Current returns null when called from a worker thread, while AsynchOperationManager.SynchronizationContext will at least return an empty SynchronizationContext so we at least have some context reference.</p>
<p><span style="font-weight: bold">Q</span>: <span style="font-style: italic">What is the difference between a ThreadBarrier and BackgroundWorker?</span><br />
<span style="font-weight: bold">A</span>: The BackgroundWorker must also be created on a UI thread. However, the BackgroundWorker does not provide an easy and transparent way (other than ReportProgress) to post events and data from the worker to the UI thread. A ThreadBarrier will support any kind of event since it uses generics.</p>
<p><span style="font-weight: bold">Q</span>: <span style="font-style: italic">Why not use WPF&#8217;s built in cross-thread binding support?</span><br />
<span style="font-weight: bold">A</span>: A ThreadBarrier can be used in combination with WPF&#8217;s cross-thread binding. The difference is that a ThreadBarrier (and events) allow arbitrary code in the UI to execute. Properties just represent data.</p>
<p><a style="font-weight: bold" href="http://www.quantumbitdesigns.com/blogposts/0019/files/ThreadBarrierExamples.zip">Download the examples</a><span style="font-weight: bold">.<br />
</span></p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fblog.quantumbitdesigns.com%2f2008%2f06%2f18%2fsimplifying-ui-and-worker-threads-threadbarrier-revisited%2f"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fblog.quantumbitdesigns.com%2f2008%2f06%2f18%2fsimplifying-ui-and-worker-threads-threadbarrier-revisited%2f" border="0" alt="kick it on DotNetKicks.com" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.quantumbitdesigns.com/2008/07/22/simplifying-ui-and-worker-threads-delegatemarshaler-revisited/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Stop Polluting the UI Thread &#8211; Use a DelegateMarshaler</title>
		<link>http://blog.quantumbitdesigns.com/2008/07/22/stop-polluting-the-ui-thread-use-a-delegatemarshaler/</link>
		<comments>http://blog.quantumbitdesigns.com/2008/07/22/stop-polluting-the-ui-thread-use-a-delegatemarshaler/#comments</comments>
		<pubDate>Wed, 23 Jul 2008 03:31:21 +0000</pubDate>
		<dc:creator>Kevin</dc:creator>
				<category><![CDATA[Multithreading]]></category>
		<category><![CDATA[Software Design]]></category>
		<category><![CDATA[DelegateMarshaler]]></category>
		<category><![CDATA[Design]]></category>

		<guid isPermaLink="false">http://blog.quantumbitdesigns.com/?p=25</guid>
		<description><![CDATA[Introduction
Update &#8211; ThreadBarrier was a poorly chosen name, use the latest DelegateMarshaler implementation instead.
With the advent of multi-core processors becoming standard in desktop PCs, it is clear we are on the verge of a shift in which high level software is designed and developed. First there was Object Oriented programming, then design patterns, and now [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Introduction</strong></p>
<p><strong>Update</strong> &#8211; ThreadBarrier was a poorly chosen name, use the latest <a href="http://blog.quantumbitdesigns.com/2008/07/22/delegatemarshaler-replace-controlinvokerequired-and-controlinvoke/">DelegateMarshaler</a> implementation instead.</p>
<p>With the advent of multi-core processors becoming standard in desktop PCs, it is clear we are on the verge of a shift in which high level software is designed and developed. First there was Object Oriented programming, then design patterns, and now there is multithreading. Multithreading has been around for decades in high end computing, but due to the now wide availability of multiple cores in a standard PC or laptop, it is only now that it is beginning to gain mainstream attention. There is a lot of work to do for tools, frameworks, and patterns to simplify the design and debugging of multithreading programs. While Microsoft has been working diligently to improve their tools (Visual Studio) and frameworks (<a href="http://www.microsoft.com/downloads/details.aspx?familyid=348F73FD-593D-4B3C-B055-694C50D2B0F3&amp;displaylang=en">Task Parallel Library</a>) to bring multithreading into the mainstream, there is not yet enough guidance and information on the internet about proper threading techniques and design patterns.</p>
<p>This is where the ‘ThreadBarrier’ pattern comes in. Ultimately it is a way to help simplify the interaction between the UI and worker threads. A ThreadBarrier is an encapsulation of thread execution inside a class such that it is not exposed to the outside world. Rather, external events are first posted to the UI thread so any listener (on the UI thread) does not have to worry about threading issues. Like any pattern, there are times where it is ideal to use and there are times where it does not apply. Use at your own discretion.</p>
<p><strong>Background</strong></p>
<p>It seems that nearly every introductory threading example on the internet consists of a button click that starts a thread that performs some operation in a worker thread in the UI code behind. While simple examples are good, this immediately introduces a developer to starting threads In UI code and thinking that such techniques are normal.</p>
<p><strong>The Problem</strong></p>
<p>The problem is that the only way most developers know how to get data back to the UI thread is to use a UI control to post back the information. In case you are new to threading: the golden rule is that all UI controls (windows, textboxes, progressbars, etc.) can only be accessed from the thread that created them (the UI thread of course). This means a worker thread cannot do myTextBox.Text=”asdf” otherwise a cross-thread exception will be thrown. Controls provide a mechanism for executing a method on the UI thread (Control.Invoke, Control.BeginInvoke, Dispatcher.Invoke, Dispatcher.BeginInvoke).</p>
<p>WinForms example:</p>
<p style="margin: 0px"><span style="color: #0000ff;">delegate</span> <span style="color: #0000ff;">void</span> <span style="color: #2b91af;">SetStartDelegate</span>(<span style="color: #0000ff;">bool</span> enabled);</p>
<p style="margin: 0px"> </p>
<p style="margin: 0px"><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">void</span> SetStartEnabled(<span style="color: #0000ff;">bool</span> enabled)</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>.buttonStart.Enabled = enabled;</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;">SetStartDelegate</span>(SetStartEnabled), <span style="color: #0000ff;">new</span> <span style="color: #0000ff;">object</span>[] { enabled });</p>
<p style="margin: 0px">}</p>
<p style="margin: 0px">}</p>
<p><!--EndFragment-->WPF example:</p>
<p style="margin: 0px"><span style="color: #0000ff;">delegate</span> <span style="color: #0000ff;">void</span> <span style="color: #2b91af;">SetStartDelegate</span>(<span style="color: #0000ff;">bool</span> enabled);</p>
<p style="margin: 0px"> </p>
<p style="margin: 0px"><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">void</span> SetStartEnabled(<span style="color: #0000ff;">bool</span> enabled)</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">if</span> (<span style="color: #0000ff;">this</span>.Dispatcher.CheckAccess() == <span style="color: #0000ff;">true</span>)</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>.buttonStart.IsEnabled = enabled;</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>.Dispatcher.Invoke(<span style="color: #2b91af;">DispatcherPriority</span>.Send, <span style="color: #0000ff;">new</span> <span style="color: #2b91af;">SetStartDelegate</span>(SetStartEnabled), enabled);</p>
<p style="margin: 0px">}</p>
<p style="margin: 0px">}</p>
<p><!--EndFragment-->There are tricks to make this a bit cleaner, but that is the common way to update the UI from any thread.</p>
<p>The combination of the Control’s UI thread rule and a Control’s ability to invoke on the UI thread essentially handcuffs developers into mixing threads with the UI and trying to make it work. Perhaps some have tried to be smart and hide the threads away deep in non-UI code to keep the UI clean. Those developers probably end up with the following questions (at least I did):</p>
<p>“How the heck do you get a control for invoking that deep in the execution and far away from the UI code? And more importantly, why does it have to be this way? There has to be a better way.”</p>
<p><strong>The Answer</strong></p>
<p>There is a better way, and it involves a <a href="http://msdn.microsoft.com/en-us/library/system.threading.synchronizationcontext.aspx">SynchronizationContext</a>. Rather than use a Control to post execution back to the UI, a SynchronizationContext provides this same capability without the UI Control requirement. Since a fantastic CodeProject <a href="http://www.codeproject.com/KB/cpp/SyncContextTutorial.aspx">article</a> already covers the SynchronizationContext in depth, a summary will only be described here.</p>
<p><strong>SynchronizationContext Overview</strong></p>
<p>-SynchronizationContext is an abstract base class for:<br />
-WindowsFormsSynchronizationContext<br />
-DispatcherSynchronizationContext<br />
-WinForms automatically creates an instance of WindowsFomsSynchronizationContext for a WinForms UI thread.<br />
-WPF automatically creates an instance of DispatcherSynchronizationContext for a WPF UI thread.<br />
-Static property AsyncOperationManager.SynchronizationContext gets the SynchronizationContext for the calling thread: WindowsFormsSynchronizationContext in WinForms and DispatcherSynchronizationContext in WPF.<br />
-SynchronizationContext provides two methods (Send and Post) for synchronous or asynchronous method invocation.<br />
-Getting AsyncOperationManager.SynchronizationContext on a non-UI thread (such as in a console app or worker thread) returns the base SynchronizationContext class that just invokes a method on the calling thread when Send is used, and calls a method on a ThreadPool thread when Post is used.</p>
<p><strong>Introducing the ThreadBarrier ‘Pattern’</strong></p>
<p>The ThreadBarrier pattern consists of a non-UI class encapsulating and executing a worker thread and always raising its events on the UI thread using a SynchronizationContext. The worker thread execution should never leave the class via events. Data and objects within the class may be operated upon by the worker thread but all external events must be called on the UI thread. If this technique is correctly followed then the listening UI code does not need to worry about thread checks and delegate posting.</p>
<p><strong>Implementing a ThreadBarrier’ (.NET 2.0)</strong></p>
<p>A ThreadBarrier can be implemented as an abstract class so that derived classes automatically inherit the necessary functionality to support the pattern.</p>
<p style="margin: 0px"><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">abstract</span> <span style="color: #0000ff;">class</span> <span style="color: #2b91af;">ThreadBarrier</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;">protected</span> ThreadBarrier()</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>._synchronizationContext = <span style="color: #2b91af;">AsyncOperationManager</span>.SynchronizationContext;</p>
<p style="margin: 0px">}</p>
<p><!--EndFragment-->The SyncronizationContext must be stored as a field so that it can be used by the worker thread in the derived class. Since the static AsyncOperationManager.SynchronizationContext property is called in the constructor, a critical requirement of properly using a ThreadBarrier derived class is that it must be created on the thread in which events want to be raised. In other words, create the class on the UI thread so that the UI’s context is captured. A worker thread can then use this context to post the methods that raise events back to the UI. The following protected method can be used for posting OnXXX methods:</p>
<p style="margin: 0px"><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">void</span> Post&lt;T&gt;(<span style="color: #2b91af;">Action</span>&lt;T&gt; raiseEventMethod, T e)</p>
<p style="margin: 0px"><span style="color: #0000ff;">where</span> T : <span style="color: #2b91af;">EventArgs</span></p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">if</span> (<span style="color: #0000ff;">this</span>._synchronizationContext == <span style="color: #0000ff;">null</span>)</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #2b91af;">ThreadPool</span>.QueueUserWorkItem(<span style="color: #0000ff;">delegate</span> { raiseEventMethod(e); });</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>._synchronizationContext.Post(<span style="color: #0000ff;">delegate</span> { raiseEventMethod(e); }, <span style="color: #0000ff;">null</span>);</p>
<p style="margin: 0px">}</p>
<p style="margin: 0px">}</p>
<p><!--EndFragment--></p>
<p style="margin: 0px">For an event such as:</p>
<p style="margin: 0px"> </p>
<p style="margin: 0px"><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">event</span> <span style="color: #2b91af;">EventHandler</span> Stopped;</p>
<p style="margin: 0px"><!--EndFragment--><span style="color: #0000ff;">protected</span> <span style="color: #0000ff;">virtual</span> <span style="color: #0000ff;">void</span> OnStopped(<span style="color: #2b91af;">EventArgs</span> e)</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">if</span> (<span style="color: #0000ff;">this</span>.Stopped != <span style="color: #0000ff;">null</span>)</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>.Stopped(<span style="color: #0000ff;">this</span>, e);</p>
<p style="margin: 0px">}</p>
<p style="margin: 0px">}</p>
<p style="margin: 0px"><!--EndFragment--><!--EndFragment--></p>
<p style="margin: 0px">A ThreadBarrier derived class simply posts events to the UI in this way:</p>
<p style="margin: 0px"> </p>
<p style="margin: 0px">Post(OnStopped, <span style="color: #2b91af;">EventArgs</span>.Empty);</p>
<p style="margin: 0px"><!--EndFragment--></p>
<p style="margin: 0px">A small example of a class implementing a ThreadBarrier would look like:</p>
<p style="margin: 0px"> </p>
<p style="margin: 0px"><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span> <span style="color: #2b91af;">WeatherChecker</span> : <span style="color: #2b91af;">ThreadBarrier</span></p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">event</span> <span style="color: #2b91af;">EventHandler</span>&lt;<span style="color: #2b91af;">WeatherEventArgs</span>&gt; TemperatureChanged;</p>
<p style="margin: 0px"><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">event</span> <span style="color: #2b91af;">EventHandler</span>&lt;<span style="color: #2b91af;">WeatherEventArgs</span>&gt; HumidityChanged;</p>
<p style="margin: 0px"><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">event</span> <span style="color: #2b91af;">EventHandler</span>&lt;<span style="color: #2b91af;">WeatherEventArgs</span>&gt; WindChanged;</p>
<p style="margin: 0px"><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">event</span> <span style="color: #2b91af;">EventHandler</span> Stopped;</p>
<p style="margin: 0px"> </p>
<p style="margin: 0px"><span style="color: #0000ff;">private</span> <span style="color: #0000ff;">bool</span> _isStopRequested;</p>
<p style="margin: 0px"><span style="color: #0000ff;">private</span> <span style="color: #2b91af;">Random</span> _random;</p>
<p style="margin: 0px"> </p>
<p style="margin: 0px"><span style="color: #0000ff;">public</span> WeatherChecker()</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>._isStopRequested = <span style="color: #0000ff;">false</span>;</p>
<p style="margin: 0px"> </p>
<p style="margin: 0px"><span style="color: #008000;">//used for generating random weather information</span></p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>._random = <span style="color: #0000ff;">new</span> <span style="color: #2b91af;">Random</span>((<span style="color: #0000ff;">int</span>)<span style="color: #2b91af;">DateTime</span>.Now.Ticks);</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> Start()</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #2b91af;">Thread</span> thread = <span style="color: #0000ff;">new</span> <span style="color: #2b91af;">Thread</span>(<span style="color: #0000ff;">new</span> <span style="color: #2b91af;">ThreadStart</span>(CheckWeather));</p>
<p style="margin: 0px">thread.IsBackground = <span style="color: #0000ff;">true</span>; <span style="color: #008000;">//prevents thread from keeping app alive when app is closed</span></p>
<p style="margin: 0px">thread.Start();</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> CheckWeather()</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">while</span> (<span style="color: #0000ff;">this</span>._isStopRequested == <span style="color: #0000ff;">false</span>)</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px">Post(OnTemperatureChanged, <span style="color: #0000ff;">new</span> <span style="color: #2b91af;">WeatherEventArgs</span>(Rand(30f)));</p>
<p style="margin: 0px">Post(OnWindChanged, <span style="color: #0000ff;">new</span> <span style="color: #2b91af;">WeatherEventArgs</span>(Rand(15f)));</p>
<p style="margin: 0px">Post(OnHumidityChanged, <span style="color: #0000ff;">new</span> <span style="color: #2b91af;">WeatherEventArgs</span>(Rand(100f)));</p>
<p style="margin: 0px"> </p>
<p style="margin: 0px"><span style="color: #008000;">//Updates roughly 4 times per second</span></p>
<p style="margin: 0px"><span style="color: #2b91af;">Thread</span>.Sleep(250);</p>
<p style="margin: 0px">}</p>
<p style="margin: 0px"> </p>
<p style="margin: 0px">Post(OnStopped, <span style="color: #2b91af;">EventArgs</span>.Empty);</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> RequestStop()</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>._isStopRequested = <span style="color: #0000ff;">true</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;">float</span> Rand(<span style="color: #0000ff;">float</span> max)</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">return</span> (<span style="color: #0000ff;">float</span>)<span style="color: #0000ff;">this</span>._random.NextDouble() * max;</p>
<p style="margin: 0px">}</p>
<p style="margin: 0px"> </p>
<p style="margin: 0px"><span style="color: #0000ff;">protected</span> <span style="color: #0000ff;">virtual</span> <span style="color: #0000ff;">void</span> OnTemperatureChanged(<span style="color: #2b91af;">WeatherEventArgs</span> e)</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">if</span> (<span style="color: #0000ff;">this</span>.TemperatureChanged != <span style="color: #0000ff;">null</span>)</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>.TemperatureChanged(<span style="color: #0000ff;">this</span>, e);</p>
<p style="margin: 0px">}</p>
<p style="margin: 0px">}</p>
<p style="margin: 0px"><span style="color: #0000ff;">protected</span> <span style="color: #0000ff;">virtual</span> <span style="color: #0000ff;">void</span> OnHumidityChanged(<span style="color: #2b91af;">WeatherEventArgs</span> e)</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">if</span> (<span style="color: #0000ff;">this</span>.HumidityChanged != <span style="color: #0000ff;">null</span>)</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>.HumidityChanged(<span style="color: #0000ff;">this</span>, e);</p>
<p style="margin: 0px">}</p>
<p style="margin: 0px">}</p>
<p style="margin: 0px"><span style="color: #0000ff;">protected</span> <span style="color: #0000ff;">virtual</span> <span style="color: #0000ff;">void</span> OnWindChanged(<span style="color: #2b91af;">WeatherEventArgs</span> e)</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">if</span> (<span style="color: #0000ff;">this</span>.WindChanged != <span style="color: #0000ff;">null</span>)</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>.WindChanged(<span style="color: #0000ff;">this</span>, e);</p>
<p style="margin: 0px">}</p>
<p style="margin: 0px">}</p>
<p style="margin: 0px"><span style="color: #0000ff;">protected</span> <span style="color: #0000ff;">virtual</span> <span style="color: #0000ff;">void</span> OnStopped(<span style="color: #2b91af;">EventArgs</span> e)</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">if</span> (<span style="color: #0000ff;">this</span>.Stopped != <span style="color: #0000ff;">null</span>)</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>.Stopped(<span style="color: #0000ff;">this</span>, e);</p>
<p style="margin: 0px">}</p>
<p style="margin: 0px">}</p>
<p style="margin: 0px">}</p>
<p style="margin: 0px"><!--EndFragment--><!--EndFragment--></p>
<p style="margin: 0px"> </p>
<p style="margin: 0px">The key points are:<br />
-WeatherChecker derives from ThreadBarrier<br />
-The worker thread is started inside this non-UI WeatherChecker class.<br />
-The WeatherChecker should be created on the UI thread.</p>
<p>Now the UI code is very clean and does not have to worry about threads:</p>
<p style="margin: 0px"><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">partial</span> <span style="color: #0000ff;">class</span> <span style="color: #2b91af;">Form1</span> : <span style="color: #2b91af;">Form</span></p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">private</span> <span style="color: #2b91af;">WeatherChecker</span> _weatherChecker;</p>
<p style="margin: 0px"> </p>
<p style="margin: 0px"><span style="color: #0000ff;">public</span> Form1()</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px">InitializeComponent();</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> buttonStart_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: #0000ff;">this</span>.buttonStart.Enabled = <span style="color: #0000ff;">false</span>;</p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>.buttonStop.Enabled = <span style="color: #0000ff;">true</span>;</p>
<p style="margin: 0px"> </p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>._weatherChecker = <span style="color: #0000ff;">new</span> <span style="color: #2b91af;">WeatherChecker</span>();</p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>._weatherChecker.TemperatureChanged += <span style="color: #0000ff;">new</span> <span style="color: #2b91af;">EventHandler</span>&lt;<span style="color: #2b91af;">WeatherEventArgs</span>&gt;(_weatherChecker_TemperatureChanged);</p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>._weatherChecker.HumidityChanged += <span style="color: #0000ff;">new</span> <span style="color: #2b91af;">EventHandler</span>&lt;<span style="color: #2b91af;">WeatherEventArgs</span>&gt;(_weatherChecker_HumidityChanged);</p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>._weatherChecker.WindChanged += <span style="color: #0000ff;">new</span> <span style="color: #2b91af;">EventHandler</span>&lt;<span style="color: #2b91af;">WeatherEventArgs</span>&gt;(_weatherChecker_WindChanged);</p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>._weatherChecker.Stopped += <span style="color: #0000ff;">new</span> <span style="color: #2b91af;">EventHandler</span>(_weatherChecker_Stopped);</p>
<p style="margin: 0px"> </p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>._weatherChecker.Start();</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> buttonStop_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: #0000ff;">this</span>._weatherChecker.RequestStop();</p>
<p style="margin: 0px">}</p>
<p style="margin: 0px"> </p>
<p style="margin: 0px"><span style="color: #0000ff;">void</span> _weatherChecker_TemperatureChanged(<span style="color: #0000ff;">object</span> sender, <span style="color: #2b91af;">WeatherEventArgs</span> e)</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>.labelTemperature.Text = <span style="color: #2b91af;">String</span>.Format(<span style="color: #a31515;">&#8220;{0:F1} C&#8221;</span>, e.Value);</p>
<p style="margin: 0px">}</p>
<p style="margin: 0px"> </p>
<p style="margin: 0px"><span style="color: #0000ff;">void</span> _weatherChecker_HumidityChanged(<span style="color: #0000ff;">object</span> sender, <span style="color: #2b91af;">WeatherEventArgs</span> e)</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>.labelHumidity.Text = <span style="color: #2b91af;">String</span>.Format(<span style="color: #a31515;">&#8220;{0:F0}%&#8221;</span>, e.Value);</p>
<p style="margin: 0px">}</p>
<p style="margin: 0px"> </p>
<p style="margin: 0px"><span style="color: #0000ff;">void</span> _weatherChecker_WindChanged(<span style="color: #0000ff;">object</span> sender, <span style="color: #2b91af;">WeatherEventArgs</span> e)</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>.labelWind.Text = <span style="color: #2b91af;">String</span>.Format(<span style="color: #a31515;">&#8220;{0:F0} mph&#8221;</span>, e.Value);</p>
<p style="margin: 0px">}</p>
<p style="margin: 0px"> </p>
<p><span style="overflow: hidden; width: 0px; position: absolute; height: 0px;"><a href="http://kvantservice.com/">????????</a></span></p>
<p style="margin: 0px"><span style="color: #0000ff;">void</span> _weatherChecker_Stopped(<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: #0000ff;">this</span>.buttonStop.Enabled = <span style="color: #0000ff;">false</span>;</p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>.buttonStart.Enabled = <span style="color: #0000ff;">true</span>;</p>
<p style="margin: 0px"> </p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>._weatherChecker = <span style="color: #0000ff;">null</span>;</p>
<p style="margin: 0px">}</p>
<p style="margin: 0px">}</p>
<p><!--EndFragment--><strong>Implementing a ThreadBarrier (.NET 3.5)</strong></p>
<p>Since the requirement of deriving from a ThreadBarrier class is not ideal, in .NET 3.5 we can use extension methods to help us do the work.</p>
<p style="margin: 0px"><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span> <span style="color: #0000ff;">class</span> <span style="color: #2b91af;">ThreadBarrierExtensions</span></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: #0000ff;">void</span> Post&lt;T&gt;(<span style="color: #0000ff;">this</span> <span style="color: #2b91af;">SynchronizationContext</span> synchronizationContext, <span style="color: #2b91af;">Action</span>&lt;T&gt; raiseEventMethod, T eventArgs)</p>
<p style="margin: 0px"><span style="color: #0000ff;">where</span> T : <span style="color: #2b91af;">EventArgs</span></p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">if</span> (synchronizationContext == <span style="color: #0000ff;">null</span>)</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #2b91af;">ThreadPool</span>.QueueUserWorkItem((e) =&gt; raiseEventMethod((T)e), eventArgs);</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">synchronizationContext.Post((e) =&gt; raiseEventMethod((T)e), eventArgs);</p>
<p style="margin: 0px">}</p>
<p style="margin: 0px">}</p>
<p style="margin: 0px">}</p>
<p style="margin: 0px"><!--EndFragment--><!--EndFragment--></p>
<p style="margin: 0px"> </p>
<p style="margin: 0px">Now the WeatherChecker class does not have to derive from a ThreadBarrier (but it now has to do the work in its constructor of saving a reference to the SynchronizationContext, the task previously left for the abstract ThreadBarrier class).:</p>
<p style="margin: 0px"> </p>
<p style="margin: 0px"><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span> <span style="color: #2b91af;">WeatherChecker</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"><span style="color: #0000ff;">&#8230;</span></p>
<p style="margin: 0px"> </p>
<p style="margin: 0px"><span style="color: #0000ff;">public</span> WeatherChecker()</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>._synchronizationContext = <span style="color: #2b91af;">AsyncOperationManager</span>.SynchronizationContext;</p>
<p style="margin: 0px"><span style="color: #0000ff;">&#8230;</span></p>
<p style="margin: 0px">}</p>
<p><!--EndFragment-->Using an extension method on the SynchronizationContext allows us to post the OnXXX method:</p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>._synchronizationContext.Post(OnTemperatureChanged, <span style="color: #0000ff;">new</span> <span style="color: #2b91af;">WeatherEventArgs</span>(Rand(30f)));</p>
<p style="margin: 0px"><!--EndFragment--></p>
<p style="margin: 0px"> </p>
<p style="margin: 0px">Using Lambda expressions also simplifies the handling of the events in the UI code:</p>
<p style="margin: 0px"> </p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>._weatherChecker.TemperatureChanged += (weatherChecker, weatherEventArgs) =&gt;</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px"><span style="color: #0000ff;">this</span>.labelTemperature.Content = <span style="color: #2b91af;">String</span>.Format(<span style="color: #a31515;">&#8220;{0:F1} C&#8221;</span>, weatherEventArgs.Value);</p>
<p style="margin: 0px">};</p>
<p><!--EndFragment--><strong>Conclusion</strong></p>
<p>The ThreadBarrier technique is an easy way to simplify the use of a worker thread and how it interacts with the UI. It is not the silver bullet for multithreading, but it does offer a way to think of a thread as an ‘object’ and hide the threading complexities. The UI and worker thread can be separated even further by designing a ThreadBarrier class to do nothing but handle events from other threading code (such as in a library that you do not have the code) and propagate just these events to the UI. This truly allows the business ‘logic’ to be free of any UI dependencies.</p>
<p><strong>Samples</strong></p>
<p><!--StartFragment --></p>
<li>ThreadBarrier Technique #1: Subclassing an existing worker thread class</li>
<li>ThreadBarrier Technique #2: Using extension methods on a SynchronizationContext</li>
<li>ThreadBarrier Technique #3: Deriving from a ThreadBarrier</li>
<li>ThreadBarrier Technique #4: Creating an instance of a ThreadBarrier</li>
<li>ThreadBarrier Technique #5: Creating an adapter class to propagate events</li>
<p><strong><a href="http://www.quantumbitdesigns.com/blogposts/0019/files/ThreadBarrierExamples.zip">Download all Samples</a></strong></p>
<p><strong>UPDATE:</strong> The DelegateMarshaler has been <a href="http://blog.quantumbitdesigns.com/2008/07/22/simplifying-ui-and-worker-threads-delegatemarshaler-revisited/">revisited</a> with a description of the 5 techniques in the sample.</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fblog.quantumbitdesigns.com%2f2008%2f06%2f10%2fstop-polluting-the-ui-thread-use-a-threadbarrier%2f"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fblog.quantumbitdesigns.com%2f2008%2f06%2f10%2fstop-polluting-the-ui-thread-use-a-threadbarrier%2f" border="0" alt="kick it on DotNetKicks.com" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.quantumbitdesigns.com/2008/07/22/stop-polluting-the-ui-thread-use-a-delegatemarshaler/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>WPF Application Design and Architecture</title>
		<link>http://blog.quantumbitdesigns.com/2008/07/22/wpf-application-design-and-architecture/</link>
		<comments>http://blog.quantumbitdesigns.com/2008/07/22/wpf-application-design-and-architecture/#comments</comments>
		<pubDate>Wed, 23 Jul 2008 03:19:27 +0000</pubDate>
		<dc:creator>Kevin</dc:creator>
				<category><![CDATA[Software Design]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[Design]]></category>
		<category><![CDATA[DM-V-VM]]></category>

		<guid isPermaLink="false">http://blog.quantumbitdesigns.com/?p=17</guid>
		<description><![CDATA[As I have been studying WPF in the past several months, I have come to at least one conclusion: The power and flexibility of WPF comes with a subtle cost. This cost is that there are 100x more ways to design an application in WPF than there is in WinForms; therefore there are 100x more [...]]]></description>
			<content:encoded><![CDATA[<p>As I have been studying WPF in the past several months, I have come to at least one conclusion: The power and flexibility of WPF comes with a subtle cost. This cost is that there are 100x more ways to design an application in WPF than there is in WinForms; therefore there are 100x more ways to shoot yourself in the foot. Fortunately, once one goes through the failures and learning cycle of WPF, it becomes much easier to design flexible and scalable applications in WPF than doing so in WinForms.</p>
<p>The purpose of this post is to illustrate the various ways a feature or WPF application can be designed.</p>
<p>This post:<br />
-Provides a peek into the vast world of WPF application designs.<br />
-Provides sample code for each design<br />
-Is for beginner/intermediate level WPF application developers.<br />
-Is not a ‘best practices’ guide, it just provides a set of examples to help readers understand how classes and interaction between objects can be designed.<br />
-Is not a ‘How-To.’ The examples are extremely contrived and few WPF features are demonstrated.</p>
<p>Before continuing I suggest reading the following articles:<br />
-<a href="http://drwpf.com/Blog/Default.aspx?tabid=36&amp;EntryID=9">Dr. WPF’s A Project Needs Structure</a><br />
-<a href="http://blogs.msdn.com/johngossman/archive/2005/10/08/478683.aspx">Introduction to Model/View/ViewModel</a><br />
-<a href="http://blogs.msdn.com/johngossman/archive/2005/10/09/478894.aspx">100 Model/View/ViewModels of Mt. Fuji</a><br />
-<a href="http://blogs.msdn.com/johngossman/archive/2006/02/26/539598.aspx">Model-View-ViewModel pattern example</a><br />
-<a href="http://blogs.msdn.com/johngossman/archive/2006/02/27/540304.aspx">ViewModel example</a><br />
-<a href="http://blogs.msdn.com/johngossman/archive/2006/03/04/543695.aspx">Advantages and disadvantages of M-V-VM</a><br />
-<a href="http://blogs.msdn.com/johngossman/archive/2006/04/13/576163.aspx">UML diagram of M-V-VM pattern</a><br />
-<a href="http://www.orbifold.net/default/?p=550">WPF Patterns</a><br />
-<a href="http://blogs.msdn.com/dancre/archive/2006/10/11/datamodel-view-viewmodel-pattern-series.aspx">Dan Crevier’s DataModel-View-ViewModel Series</a><br />
-<a href="http://www.thoughtclusters.com/2007/12/datamodel-and-viewmodel.html">DataModel and VIewModel</a></p>
<p>I also recommend studying the source and design of the following applications:<br />
-<a href="http://www.codeplex.com/familyshow">Family.Show</a><br />
-<a href="http://windowsclient.net/wpf/starter-kits/sce.aspx">SceReader</a></p>
<p>If all of these concepts are new to you, it can be a bit overwhelming. It is a lot of information and concepts to absorb. Hopefully the samples provided in this post can make it easier to understand how these concepts can come into play in a real-world application. Four designs will be demonstrated, starting from an extremely simple design all the way to one that uses DataModel-View-ViewModel. Each sample has the same features to make it easier to follow along the evolution of the design.</p>
<p>The features that are demonstrated are as follows:<br />
-Two buttons allow a user to find currently loaded assemblies and types<br />
-A textbox allows the search to be filtered.<br />
-The results are displayed in a listbox</p>
<p><img align="middle" width="450" src="http://www.quantumbitdesigns.com/blogposts/0007/img/SampleSS.png" height="350" style="width: 450px; height: 350px" /></p>
<p>Download the samples: <a href="http://www.quantumbitdesigns.com/blogposts/0007/files/WpfDesigns.zip">WPFDesigns</a><br />
I recommend browsing the source and following along as each sample and design is explained.</p>
<p><strong>Design #1</strong></p>
<p>For such a simple application, it really does not take much to implement the solution using just a window with some buttons and a ListBox on it. When a button is clicked, a handler can call a method and update the listbox’s ItemsSource directly.</p>
<p>        public void ShowTypes_Click(object sender, RoutedEventArgs e)<br />
        {<br />
            this.ResultsListBox.ItemsSource = FindTypeNames();<br />
        }</p>
<p><img align="middle" width="720" src="http://www.quantumbitdesigns.com/blogposts/0007/img/Design1.png" height="378" style="width: 720px; height: 378px" /></p>
<p>1. A button is clicked and handled in Window1’s code behind.<br />
2. The loaded types are retrieved.<br />
3. The ListBox’s ItemsSource is updated</p>
<p><strong>Design #2</strong></p>
<p>In this sample the buttons and textbox are moved onto their own user control, while the ListBox is moved to its own user control as well. Breaking up a UI into modular components allows the UI to remain simple as many features are added, and forces the logic handling to be more modular as well.</p>
<p>&lt;UserControl x:Class=&#8221;WpfDesigns2.Controls.OperationsUserControl&#8221;<br />
    xmlns=&#8221;<a href="http://schemas.microsoft.com/winfx/2006/xaml/presentation">http://schemas.microsoft.com/winfx/2006/xaml/presentation</a>&#8221;<br />
    xmlns:x=&#8221;<a href="http://schemas.microsoft.com/winfx/2006/xaml">http://schemas.microsoft.com/winfx/2006/xaml</a>&#8221;<br />
    DataContext=&#8221;{Binding RelativeSource={RelativeSource Self}}&#8221;&gt;<br />
    &lt;Grid&gt;<br />
      &lt;StackPanel&gt;<br />
        &lt;Button Click=&#8221;ShowAssemblies_Click&#8221;&gt;Show Assemblies&lt;/Button&gt;<br />
        &lt;Button Click=&#8221;ShowTypes_Click&#8221;&gt;Show Types&lt;/Button&gt;<br />
        &lt;TextBlock&gt;Match:&lt;/TextBlock&gt;<br />
        &lt;TextBox Width=&#8221;80&#8243; Text=&#8221;{Binding Path=MatchText}&#8221;/&gt;<br />
      &lt;/StackPanel&gt;<br />
    &lt;/Grid&gt;<br />
&lt;/UserControl&gt;</p>
<p>Now that each user control is handling its own events there needs to be some way to get the results from one user control to the other. Since the Window1 is hosting both user controls, in this sample we will make it listen to an operation complete event that contains the results, and then send those results to the user control with the ListBox so it can be updated.</p>
<p><img align="middle" width="720" src="http://www.quantumbitdesigns.com/blogposts/0007/img/Design2.png" height="486" style="width: 720px; height: 486px" /></p>
<p>1. The button click is handled in the Operations user control.<br />
2. Using the MatchText variable and a ReflectionHelper object that exists in the Operations user control, the assemblies or types are retrieved.<br />
3. The user control raises an event letting listeners know the results are complete.<br />
4. Window1 handles the event and sends the results to the ReflectionResults property of the user control with the ListBox.<br />
5. Since the ListBox is bound to the ReflectionResults dependency property, the ListBox UI is updated automatically.</p>
<p><strong>Design #3</strong></p>
<p>This sample takes the design a step further and breaks the UI from the logic. You can think of the user controls as the View and the logic as the Model. A manager called ApplicationManager was designed to contain all of the objects in the model. This manager is created in Window1’s XAML:</p>
<p>    &lt;ObjectDataProvider x:Key=&#8221;ApplicationManager&#8221; ObjectType=&#8221;{x:Type local:ApplicationManager}&#8221; /&gt;</p>
<p>Since Window1 contains the manager in its resources collection, it can pass on the manager’s child models to each respective user control:</p>
<p>      &lt;controls:OperationsUserControl<br />
        Grid.Column=&#8221;0&#8243;<br />
        x:Name=&#8221;OperationsControl&#8221;<br />
        DataContext=&#8221;{Binding Source={StaticResource ApplicationManager}, Path=ReflectionHelper}&#8221;/&gt;<br />
      &lt;controls:ReflectionResultsUserControl<br />
        Grid.Column=&#8221;1&#8243;<br />
        x:Name=&#8221;ReflectionDisplayControl&#8221;<br />
        DataContext=&#8221;{Binding Source={StaticResource ApplicationManager}, Path=ReflectionResults}&#8221;/&gt;</p>
<p>Now each user control’s DataContext is set to an object from the Model layer, so that the UI elements can bind to a single model element. When the user control needs to get its model object, it can do so in the following way:</p>
<p>        private ReflectionHelper ReflectionHelper<br />
        {<br />
            get<br />
            {<br />
                return this.DataContext as ReflectionHelper;<br />
            }<br />
        }</p>
<p>A button click in the handler is as easy as:</p>
<p>        public void ShowTypes_Click(object sender, RoutedEventArgs e)<br />
        {<br />
            this.ReflectionHelper.FindTypes();<br />
        }</p>
<p>In this sample the ApplicationManager is handling listening for the results from one model and passing the data on to the results model. This separates the logic from the views. Since the ReflectionResultsUserControl is bound to the Results property on the results model, it gets updated automatically when the ApplicationManager updates the results model. At this stage the UserControls are doing virtually nothing and the model layer is doing all of the work (which is ideal).</p>
<p><img align="middle" width="720" src="http://www.quantumbitdesigns.com/blogposts/0007/img/Design3.png" height="477" style="width: 720px; height: 477px" /></p>
<p>1. The button click is handled in the OperationsUserControl.<br />
2. The FindTypes or FindAssemblies method is called on the user control’s model element.<br />
3. The reflection helper model element does some reflection work<br />
4. When the work is complete an event is raised<br />
5. The ApplicationManager listening for the event updates the ReflectionResults model element.<br />
6. Since the ReflectionResultsUserControl’s ListBox is bound to the Results property of the ReflectionResults model element, the ListBox is updated automatically.</p>
<p><strong>Design #4</strong></p>
<p>At this point we have probably taken the samples as far as they need to go. However, to demonstrate one way the DataModel-View-ViewModel pattern can be implemented, sample #4 takes the design to the next level. Since the other DataModel-View-ViewModel articles already do a great job explaining the concepts, I will just describe the design for sample #4. Let’s start with the diagram:</p>
<p><img align="middle" width="720" src="http://www.quantumbitdesigns.com/blogposts/0007/img/Design4.png" height="576" style="width: 720px; height: 576px" /></p>
<p>1. Using a RoutedCommand the OperationsView handles the button click command.<br />
2. The view calls into its view model to perform an operation.<br />
3. Since the OperationsViewModel was storing the MatchText data, it can call into its model (ReflectionHelper) to find types or assemblies.<br />
4. The ReflectionHelper model retrieves the matching types or assemblies.<br />
5. The ReflectionHelper raises its operations complete event<br />
6. The ApplicationManager handles the event and updates the ReflectionResults model.<br />
7. The ReflectionResults model raises a results changed event<br />
8. The ReflectionResultsVewModel handles the event and puts the results data into a format suitable for its view.<br />
9. Since the ListBox in the ReflectionResultsView is bound to the ObservableCollection in its respective view model, the ListBox is updated automatically.</p>
<p>For such a small application this design is overkill. However, as applications grow in size and complexity, the DataModel-View-ViewModel pattern keeps the overall design simple and minimizes dependencies. It also has the added benefit of making all of the various modules much easier to test, which is obviously crucial to the success of any large piece of software.</p>
<p>One interesting aspect of the DM-V-VM is how well the view can be abstracted from the rest of the application. For example, in this sample a new class call ApplicationViewState was created to hold the view models that represent the views. A DataTemplate allows us to represent the view model in any way we want:</p>
<p>  &lt;DataTemplate DataType=&#8221;{x:Type viewModels:OperationsViewModel}&#8221;&gt;<br />
    &lt;!&#8211;Sets the view model as the data context&#8211;&gt;<br />
    &lt;views:OperationsView DataContext=&#8221;{Binding}&#8221; /&gt;<br />
  &lt;/DataTemplate&gt;</p>
<p>In the main window a ContentPresenter is used to represent a ‘place holder’ for its content which is specified to be one of the view models:</p>
<p>      &lt;ContentPresenter<br />
        Grid.Column=&#8221;0&#8243;<br />
        Content=&#8221;{Binding Source={StaticResource ApplicationManager}, Path=ViewState.LeftSideView}&#8221;/&gt;<br />
      &lt;ContentPresenter<br />
        Grid.Column=&#8221;1&#8243;<br />
        Content=&#8221;{Binding Source={StaticResource ApplicationManager}, Path=ViewState.RightSideView}&#8221;/&gt;</p>
<p>By swapping the view models in the ApplicationViewState, the views automatically follow their respective view model. This is a crude demonstration of a data driven UI.</p>
<p><strong>Disclaimer</strong>: Design #4’s sample is not a perfect implementation of the DM-V-VM pattern. I have seen it implemented in various different ways. It usually depends on the requirements of the particular application. As far as I can tell there is also no difference between what people call a DataModel and a Model. Since many WPF applications work with a data layer of some sort such as a database, they call it the DataModel. In this last sample I could have easily just called the ReflectionHelper and ReflectionResults Models (I think I did a few times anyways).</p>
<p><strong>A Word of Warning</strong>: If you are new to WPF, attempting to implement DM-V-VM for your application is extremely difficult. There are many ‘gotchas’ along the way that put major roadblocks in the way of solving problems. Most of these are WPF specific. Your best source of help is the <a href="http://forums.microsoft.com/MSDN/ShowForum.aspx?ForumID=119&amp;SiteID=1">MSDN WPF Forum</a>.</p>
<p>In the real world, applications are usually a mix of all four of these designs. No single design fits every application. It is up to you to learn from your mistakes in order to learn how to design and develop simple, flexible, scalable applications. <img src='http://blog.quantumbitdesigns.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  No matter how experienced you get, there is always more to learn!</p>
<p>Download the samples: <a href="http://www.quantumbitdesigns.com/blogposts/0007/files/WpfDesigns.zip">WPFDesigns</a></p>
<p>All questions, comments, and criticism are welcome!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.quantumbitdesigns.com/2008/07/22/wpf-application-design-and-architecture/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
