<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0"><channel><title>LA.NET [EN]</title><link>http://msmvps.com/blogs/luisabreu/default.aspx</link><description>Ramblings about C#, .NET and Programming</description><dc:language>en</dc:language><generator>CommunityServer 2008.5 SP2 (Build: 40407.4157)</generator><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" href="http://feeds.feedburner.com/Laneten" type="application/rss+xml" /><item><title>Multithreading: a final example on how CompareExchange might help you</title><link>http://feedproxy.google.com/~r/Laneten/~3/LqqUUNFIKZI/multithreading-a-final-example-on-how-compareexchange-might-help-you.aspx</link><pubDate>Sat, 04 Jul 2009 15:31:44 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1697975</guid><dc:creator>luisabreu</dc:creator><slash:comments>0</slash:comments><wfw:commentRss>http://msmvps.com/blogs/luisabreu/rsscomments.aspx?PostID=1697975</wfw:commentRss><comments>http://msmvps.com/blogs/luisabreu/archive/2009/07/04/multithreading-a-final-example-on-how-compareexchange-might-help-you.aspx#comments</comments><description>&lt;p&gt;In the last posts we’ve been poking around memory models, &lt;a href="http://msmvps.com/blogs/luisabreu/archive/2009/07/03/multithreading-introducing-memory-fences.aspx"&gt;memory&lt;/a&gt; &lt;a href="http://msmvps.com/blogs/luisabreu/archive/2009/07/03/multithreading-using-fences-from-net-code.aspx"&gt;fences&lt;/a&gt; and other interesting things that might lead to the so called lock free programming. Before keep looking at how we can use those features from our C# code, I’d like to add one more example that shows how the interlocked operations might help you in the real world. Do you recall our &lt;a href="http://msmvps.com/blogs/luisabreu/archive/2009/06/15/multithreading-implementing-the-iasyncresult-interface.aspx"&gt;implementation&lt;/a&gt; of the IAsyncResult interface? &lt;/p&gt;  &lt;p&gt;At the time, we’ve used a lock for ensuring proper access and initialization of our manual reset event used for signaling the end of the operation. Now that we’ve met interlocked operations, we can improve that code and get rid of the lock. Let’s focus on the private GetEvtHandle method:&lt;/p&gt;  &lt;pre style="background-color:black;" class="code"&gt;&lt;span style="color:#ff8000;"&gt;private &lt;/span&gt;&lt;span style="color:yellow;"&gt;ManualResetEvent &lt;/span&gt;&lt;span style="color:white;"&gt;GetEvtHandle() {
  &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;var &lt;/span&gt;&lt;span style="color:white;"&gt;newEvt = &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;new &lt;/span&gt;&lt;span style="color:yellow;"&gt;ManualResetEvent&lt;/span&gt;&lt;span style="color:white;"&gt;(&lt;/span&gt;&lt;span style="color:#ff8000;"&gt;false&lt;/span&gt;&lt;span style="color:white;"&gt;);
  &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;if &lt;/span&gt;&lt;span style="color:white;"&gt;(&lt;/span&gt;&lt;span style="color:yellow;"&gt;Interlocked&lt;/span&gt;&lt;span style="color:white;"&gt;.CompareExchange(&lt;/span&gt;&lt;span style="color:#ff8000;"&gt;ref &lt;/span&gt;&lt;span style="color:white;"&gt;_evt, newEvt, &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;null&lt;/span&gt;&lt;span style="color:white;"&gt;) != &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;null&lt;/span&gt;&lt;span style="color:white;"&gt;) {
    newEvt.Close();
  }      
  &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;if &lt;/span&gt;&lt;span style="color:white;"&gt;(_isCompleted) {
    _evt.Set();
  }      
  &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;return &lt;/span&gt;&lt;span style="color:white;"&gt;_evt;
}&lt;/span&gt;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;As you can see, we’ve replaced the lock with a CompareExchange method call for ensuring proper atomic update: if the _evt field is null, then set it to newEvt (which, if you recall our previous post on interlocked operations, will only happen when that value is null!). Since the method returns the old value, if we get anything different from null, then it means that some other thread already set the field to a valid value. When that happens, we need to clean up and close the manual reset event we’ve just created. And there you go: the lock is gone.&lt;/p&gt;

&lt;p&gt;As you’ve probably guessed, This strategy can be adjusted to objects that implement the IDisposable interface and you can use it when the creation of new objects isn’t too expensive and you need to have only a single instance of an item (in other words, it might be a valid option for implementing singletons in multithreading scenarios).&lt;/p&gt;

&lt;p&gt;And that’s it. Keep tuned for more on multithreading.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1697975" width="1" height="1"&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/bpq3zyGrZGz8Wo1pmxZBz_WsVeo/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/bpq3zyGrZGz8Wo1pmxZBz_WsVeo/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/bpq3zyGrZGz8Wo1pmxZBz_WsVeo/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/bpq3zyGrZGz8Wo1pmxZBz_WsVeo/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;</description><category domain="http://msmvps.com/blogs/luisabreu/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://msmvps.com/blogs/luisabreu/archive/tags/Multithreading/default.aspx">Multithreading</category><feedburner:origLink>http://msmvps.com/blogs/luisabreu/archive/2009/07/04/multithreading-a-final-example-on-how-compareexchange-might-help-you.aspx</feedburner:origLink></item><item><title>Multithreading: using fences from .NET code</title><link>http://feedproxy.google.com/~r/Laneten/~3/8VNaPmkOLEg/multithreading-using-fences-from-net-code.aspx</link><pubDate>Fri, 03 Jul 2009 14:28:13 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1697699</guid><dc:creator>luisabreu</dc:creator><slash:comments>0</slash:comments><wfw:commentRss>http://msmvps.com/blogs/luisabreu/rsscomments.aspx?PostID=1697699</wfw:commentRss><comments>http://msmvps.com/blogs/luisabreu/archive/2009/07/03/multithreading-using-fences-from-net-code.aspx#comments</comments><description>&lt;p&gt;In the last &lt;a href="http://msmvps.com/blogs/luisabreu/archive/2009/07/03/multithreading-introducing-memory-fences.aspx"&gt;post&lt;/a&gt;, we’ve talked about memory fences. Today we’re going to keep looking at this topic, but we’re turning our attention to coding, ie, we’re going to talk about the options we have to add fences to our classes. In .NET, things are relatively straightforward. &lt;/p&gt;  &lt;p&gt;Whenever we use one of the interlocked methods we’ve &lt;a href="http://msmvps.com/blogs/luisabreu/archive/2009/07/02/multithreading-introducing-the-interlocked-operations.aspx"&gt;met&lt;/a&gt; in the past, we’re adding a full fence to our code. Locking will also end up using full fences. As you can see,&amp;#160; you’re already using full fences in several places. The good news is that you can also be specific about them, ie, there’s a method you can call if you want to add a fence to your code in a specific place: I’m talking about the &lt;a href="http://msdn.microsoft.com/en-us/library/system.threading.thread.memorybarrier.aspx"&gt;Thread.MemoryBarrier&lt;/a&gt; static method (btw, this method will also add a&amp;#160; full fence).&lt;/p&gt;  &lt;p&gt;Volatile reads or writes generate fences too! In C#, you can use the &lt;a href="http://msdn.microsoft.com/en-us/library/x13ttww7(VS.71).aspx"&gt;volatile&lt;/a&gt; keyword to mark a field as volatile. Reading a &lt;a href="http://msdn.microsoft.com/en-us/library/x13ttww7(VS.71).aspx"&gt;volatile&lt;/a&gt; field is the “equivalent” of having an acquiring fence. Writing to a &lt;a href="http://msdn.microsoft.com/en-us/library/x13ttww7(VS.71).aspx"&gt;volatile&lt;/a&gt; field can be seen as “adding” a release fence. Now, it’s important to notice that you’ll always get these read and write behaviors whenever you use the volatile field. If you’re looking for more control (ex.: you’ll only interested in having an acquire fence for a read), then you should rely on the &lt;a href="http://msdn.microsoft.com/en-us/library/system.threading.thread.volatileread.aspx"&gt;Thread.VolatileRead&lt;/a&gt; or &lt;a href="http://msdn.microsoft.com/en-us/library/system.threading.thread.volatilewrite.aspx"&gt;Thread.VolatileWrite&lt;/a&gt; methods for ensuring proper the desired behavior.&lt;/p&gt;  &lt;p&gt;And I guess that’s all there’s time for today. In the next post, we’ll keep looking at multithreading and see how we can use these features on a C# program. Keep tuned!&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1697699" width="1" height="1"&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/Dgcp2taDVupkQS6AxDXvAFqKGpY/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/Dgcp2taDVupkQS6AxDXvAFqKGpY/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/Dgcp2taDVupkQS6AxDXvAFqKGpY/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/Dgcp2taDVupkQS6AxDXvAFqKGpY/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;</description><category domain="http://msmvps.com/blogs/luisabreu/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://msmvps.com/blogs/luisabreu/archive/tags/Multithreading/default.aspx">Multithreading</category><feedburner:origLink>http://msmvps.com/blogs/luisabreu/archive/2009/07/03/multithreading-using-fences-from-net-code.aspx</feedburner:origLink></item><item><title>Multithreading: introducing memory fences</title><link>http://feedproxy.google.com/~r/Laneten/~3/uysqDDAJrKY/multithreading-introducing-memory-fences.aspx</link><pubDate>Fri, 03 Jul 2009 12:58:22 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1697685</guid><dc:creator>luisabreu</dc:creator><slash:comments>2</slash:comments><wfw:commentRss>http://msmvps.com/blogs/luisabreu/rsscomments.aspx?PostID=1697685</wfw:commentRss><comments>http://msmvps.com/blogs/luisabreu/archive/2009/07/03/multithreading-introducing-memory-fences.aspx#comments</comments><description>&lt;p&gt;A few posts back, we’ve introduced the &lt;a href="http://msmvps.com/blogs/luisabreu/archive/2009/06/29/multithreading-load-and-store-reordering.aspx"&gt;concept&lt;/a&gt; of load and store reordering. As we’ve seen, reordering operations exist as a way of improving performance and can be introduced on several levels (starting at compilation time and ending at runtime when the processor executes the instructions). We &lt;a href="http://msmvps.com/blogs/luisabreu/archive/2009/06/29/multithreading-load-and-store-reordering.aspx"&gt;saw&lt;/a&gt; that even though things can get chaotic quickly, there are some guarantees we can hold on to when writing multithreaded code. One of those guarantees is that all platforms respect a specific memory model and that’s what we’ll be talking about in this post.&lt;/p&gt;  &lt;p&gt;A memory model defines which kinds of moves may occur&amp;#160; (ie, which loads and stores can be moved). If you’ve got a weak memory model, then you’ll get plenty of allowable moves and this will lead to a superior performance. However, you’ll also need to pay lots of attention to the code you write. Allowing less moves will, of course, lead to less complexity but won’t give you (hum…I mean, the compiler and processor) that many chances for updating your code.&lt;/p&gt;  &lt;p&gt;Since we’re talking about .NET here, we’ll focus the rest of the post on the valid assumptions for the CLR. The CLR has a strong memory model. In practice, this means that several compiler optimizations are forbidden&amp;#160; and that it should be fairly easy (sort of…) to write code that is portable across several architectures where the code might run. Before going on, it’s important to notice that the CLR memory model is tighter than the one you get in the ECMA spec.&lt;/p&gt;  &lt;p&gt;In the CLR, you can get reordering for load/load, load/store and store/load. The only one which isn’t permitted is store/store reordering (meaning that a store can never move after another store). Volatile loads and stores are different and only allow store/load reordering (we’ll be talking about volatiles in future posts). Btw, the ECMA specification allows all these move types.&lt;/p&gt;  &lt;p&gt;Ok, so if those store and load reordering are allowed, how can we stopped them from happening? ah, glad you asked! We can use fences (or barriers) to ensure that they don’t occur at specific times.&lt;/p&gt;  &lt;p&gt;A fence (aka barrier) prevents memory loads and stores reordering from happening. There are several types of fences. Full fences are probably the most known and used type. A full fence ensures that no load or stores moves across the fence (ie, no load or store before the fence can move after it nor any load or store placed after the fence may move before it).&lt;/p&gt;  &lt;p&gt;Besides the ubiquitous full fence (which is available everywhere), there are other variations. With Store fences, no store can move over the fence (it’s ok for reorders to happen with loads). Load fences are similar, but in this case, only loads are “fixed”.&lt;/p&gt;  &lt;p&gt;Finally, there’s also a couple of “one way” fences: acquire and release fences. Acquire fences ensures that no memory operation that happens after the fence can be moved before the fence. Release fences work the other way around: instructions defined after the fence may happen before the fence but no “pre-fence” instruction may happen after the fence. &lt;/p&gt;  &lt;p&gt;As you might have guessed by now, fences load to a more sequential model which will, without any doubt, lead to a degradation of your application. This means that you should apply them carefully. Yes, we do need fences, but do keep in mind that using them will reduce the ability for reordering and improving the code you write.&lt;/p&gt;  &lt;p&gt;By now, I guess that we’ve covered most of the theory around fences. You might be asking: how do I use fences in my .NET code. Good question, but we’ll leave the answer for the next post. Keep tuned for more on multithreading.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1697685" width="1" height="1"&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/Wotn3zMGJYCdYhRH4J-5yxpXhAE/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/Wotn3zMGJYCdYhRH4J-5yxpXhAE/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/Wotn3zMGJYCdYhRH4J-5yxpXhAE/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/Wotn3zMGJYCdYhRH4J-5yxpXhAE/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;</description><category domain="http://msmvps.com/blogs/luisabreu/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://msmvps.com/blogs/luisabreu/archive/tags/Multithreading/default.aspx">Multithreading</category><feedburner:origLink>http://msmvps.com/blogs/luisabreu/archive/2009/07/03/multithreading-introducing-memory-fences.aspx</feedburner:origLink></item><item><title>Multithreading: when interlocked operations aren’t enough</title><link>http://feedproxy.google.com/~r/Laneten/~3/ys-wRba6XcQ/multithreading-when-interlocked-operations-aren-t-enough.aspx</link><pubDate>Thu, 02 Jul 2009 14:45:30 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1697578</guid><dc:creator>luisabreu</dc:creator><slash:comments>1</slash:comments><wfw:commentRss>http://msmvps.com/blogs/luisabreu/rsscomments.aspx?PostID=1697578</wfw:commentRss><comments>http://msmvps.com/blogs/luisabreu/archive/2009/07/02/multithreading-when-interlocked-operations-aren-t-enough.aspx#comments</comments><description>&lt;p&gt;In the previous &lt;a href="http://msmvps.com/blogs/luisabreu/archive/2009/07/02/multithreading-introducing-the-interlocked-operations.aspx"&gt;post&lt;/a&gt;, we’ve started looking at interlocked operations. As we’ve seen, interlocked operations are great at what they do but they won’t be usable in all scenarios (ie, don’t think that they’ll solve all your locks problems). To show how things might go awry when using interlocks, I’ll reuse a great &lt;a href="http://blogs.msdn.com/oldnewthing/archive/2004/09/15/229915.aspx"&gt;example&lt;/a&gt; written by &lt;a href="http://blogs.msdn.com/oldnewthing/default.aspx"&gt;Raymond Chen&lt;/a&gt; a few years ago (I’m updating it to C#):&lt;/p&gt;  &lt;pre style="background-color:black;" class="code"&gt;&lt;span style="color:#ff8000;"&gt;class &lt;/span&gt;&lt;span style="color:yellow;"&gt;Program 
&lt;/span&gt;&lt;span style="color:white;"&gt;{
  &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;private static &lt;/span&gt;&lt;span style="color:yellow;"&gt;Object &lt;/span&gt;&lt;span style="color:white;"&gt;_lock = &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;new &lt;/span&gt;&lt;span style="color:yellow;"&gt;Object&lt;/span&gt;&lt;span style="color:white;"&gt;();
  &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Int64 &lt;/span&gt;&lt;span style="color:white;"&gt;InterlockedMultiply(&lt;br /&gt;          &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;ref &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Int64 &lt;/span&gt;&lt;span style="color:white;"&gt;multiplicand, &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Int64 &lt;/span&gt;&lt;span style="color:white;"&gt;multiplier) {
    &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Int64 &lt;/span&gt;&lt;span style="color:white;"&gt;result = 0;
    &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;lock &lt;/span&gt;&lt;span style="color:white;"&gt;(_lock) {
      &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;var &lt;/span&gt;&lt;span style="color:white;"&gt;aux = multiplicand;
      &lt;/span&gt;&lt;span style="color:yellow;"&gt;Thread&lt;/span&gt;&lt;span style="color:white;"&gt;.Sleep(100);//oops!!!
      result = multiplicand = aux * multiplier;          
    }
    &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;return &lt;/span&gt;&lt;span style="color:white;"&gt;result;
  }      
  &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;static void &lt;/span&gt;&lt;span style="color:white;"&gt;Main(&lt;/span&gt;&lt;span style="color:#ff8000;"&gt;string&lt;/span&gt;&lt;span style="color:white;"&gt;[] args) {
      &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Int64 &lt;/span&gt;&lt;span style="color:white;"&gt;a = 5;
      &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;new &lt;/span&gt;&lt;span style="color:yellow;"&gt;Thread&lt;/span&gt;&lt;span style="color:white;"&gt;(&lt;br /&gt;         () =&amp;gt; InterlockedMultiply(&lt;/span&gt;&lt;span style="color:#ff8000;"&gt;ref &lt;/span&gt;&lt;span style="color:white;"&gt;a, 5)).Start();
      &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;new &lt;/span&gt;&lt;span style="color:yellow;"&gt;Thread&lt;/span&gt;&lt;span style="color:white;"&gt;(() =&amp;gt; { &lt;br /&gt;              &lt;/span&gt;&lt;span style="color:yellow;"&gt;Thread&lt;/span&gt;&lt;span style="color:white;"&gt;.Sleep(50); &lt;br /&gt;              &lt;/span&gt;&lt;span style="color:yellow;"&gt;Interlocked&lt;/span&gt;&lt;span style="color:white;"&gt;.Increment(&lt;/span&gt;&lt;span style="color:#ff8000;"&gt;ref &lt;/span&gt;&lt;span style="color:white;"&gt;a); }).Start();
      &lt;/span&gt;&lt;span style="color:yellow;"&gt;Thread&lt;/span&gt;&lt;span style="color:white;"&gt;.Sleep(2000);
      &lt;/span&gt;&lt;span style="color:yellow;"&gt;Console&lt;/span&gt;&lt;span style="color:white;"&gt;.WriteLine(a);
  }
}&lt;/span&gt;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;The idea is to add a safe multiplier method. As we’ve seen in the previous &lt;a href="http://msmvps.com/blogs/luisabreu/archive/2009/07/02/multithreading-introducing-the-interlocked-operations.aspx"&gt;post&lt;/a&gt;, interlocked increments are atomic. That means that they’re executed as a “single” operation by the processor. Since we didn’t had a method that performs the same operation for multiplication, we’ve decided to mimic that behavior by adding a new method which uses a lock to ensure proper multiplication.&lt;/p&gt;

&lt;p&gt;If I asked you what Console.WriteLine(a) would print, what would you say? For now, forget those nasty Sleep invocations (they’re there to force the wrong behavior)… I’m guessing that you’d probably say that Console.WriteLine will only write 26 or 30. It will write 26 if InterlockedMultiply “beats” Increment or 30 if Increment is run before InterlockedMultiply. Ah, well, with those nasty sleep instructions, I’ve managed to get 25 here on my machine. Wtf? How? Why?&lt;/p&gt;

&lt;p&gt;Well, what happened is logical…Interlocked.Increment will always update the value in a single atomic operation (this means it will load, update and then store the value in a “single” step). However, InterlockedMultiply only ensures that the code wrapped by the lock will only be executed by a thread at a time. Look at that method carefully…can you see a load followed by a store? Those two operations aren’t performed atomically like the one you get through the Interlocked.Increment method!&lt;/p&gt;

&lt;p&gt;There is a solution to this problem, but it involves looping until you get a valid result. Take a look at the method updated to work correctly:&lt;/p&gt;

&lt;pre style="background-color:black;" class="code"&gt;&lt;span style="color:#ff8000;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Int64 &lt;/span&gt;&lt;span style="color:white;"&gt;InterlockedMultiply(&lt;br /&gt;       &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;ref &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Int64 &lt;/span&gt;&lt;span style="color:white;"&gt;multiplicand, &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Int64 &lt;/span&gt;&lt;span style="color:white;"&gt;multiplier) {
  &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Int64 &lt;/span&gt;&lt;span style="color:white;"&gt;result = 0;
  &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Int64 &lt;/span&gt;&lt;span style="color:white;"&gt;aux = 0;
  &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;do &lt;/span&gt;&lt;span style="color:white;"&gt;{
    aux = multiplicand;
    result = aux * multiplier;
  } &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;while &lt;/span&gt;&lt;span style="color:white;"&gt;( &lt;/span&gt;&lt;span style="color:yellow;"&gt;Interlocked&lt;/span&gt;&lt;span style="color:white;"&gt;.CompareExchange(&lt;br /&gt;                &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;ref &lt;/span&gt;&lt;span style="color:white;"&gt;multiplicand, result, aux) != aux);
  &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;return &lt;/span&gt;&lt;span style="color:white;"&gt;result;
}    &lt;/span&gt;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;As you can see, we’re using the &lt;a href="http://msdn.microsoft.com/en-us/library/yss0xc74.aspx"&gt;Interlocked.CompareExchange&lt;/a&gt; method to ensure that multiplicand will only be updated if it hasn’t changed during the&amp;#160; execution of that loop. That happens because the &lt;a href="http://msdn.microsoft.com/en-us/library/yss0xc74.aspx"&gt;Interlocked.CompareExchange&lt;/a&gt; method will always return the value that was stored in multiplicand at the time of the call (recall that &lt;a href="http://msdn.microsoft.com/en-us/library/yss0xc74.aspx"&gt;CompareExchange&lt;/a&gt; always returns the original value of the 1st parameter passed to the method at the time of the call).&lt;/p&gt;

&lt;p&gt;As you can see, interlocked operations don’t ensure proper serialization of your code. They only guarantee that the interlocked operation is done atomically. And I guess that’s all for now. Keep tuned for more on multithreading.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1697578" width="1" height="1"&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/i58y94m9O38SOh7hAdrQqt-Gwi4/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/i58y94m9O38SOh7hAdrQqt-Gwi4/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/i58y94m9O38SOh7hAdrQqt-Gwi4/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/i58y94m9O38SOh7hAdrQqt-Gwi4/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;</description><category domain="http://msmvps.com/blogs/luisabreu/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://msmvps.com/blogs/luisabreu/archive/tags/Multithreading/default.aspx">Multithreading</category><feedburner:origLink>http://msmvps.com/blogs/luisabreu/archive/2009/07/02/multithreading-when-interlocked-operations-aren-t-enough.aspx</feedburner:origLink></item><item><title>Multithreading: introducing the interlocked operations</title><link>http://feedproxy.google.com/~r/Laneten/~3/kl_AGtVTFoE/multithreading-introducing-the-interlocked-operations.aspx</link><pubDate>Thu, 02 Jul 2009 11:58:04 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1697571</guid><dc:creator>luisabreu</dc:creator><slash:comments>3</slash:comments><wfw:commentRss>http://msmvps.com/blogs/luisabreu/rsscomments.aspx?PostID=1697571</wfw:commentRss><comments>http://msmvps.com/blogs/luisabreu/archive/2009/07/02/multithreading-introducing-the-interlocked-operations.aspx#comments</comments><description>&lt;p&gt;As we’ve seen in the previous &lt;a href="http://msmvps.com/blogs/luisabreu/archive/2009/06/29/multithreading-hardware-atomicity.aspx"&gt;post&lt;/a&gt;, most processors give us important insurances regarding memory loads and stores. However, even though those insurances are important and can be used in several scenarios, the truth is that they aren’t enough for all real world tasks.&lt;/p&gt;  &lt;p&gt;Fortunately, most processors also offer a group of interlocked operations which enable atomic compare and swap scenarios. These operations rely on hardware and interprocess synchronization. Notice that these operations aren’t as simply as they might seem at first sight. For instance, it’s important to recall that in today’s architectures, these kind of operations need to play well with caches. My point is that event though these operations tend to be cheaper that the traditional locks, they’re still not cheap (for instance, there are cases where an interlocked operation ends up locking the bus and that is not a good thing).&lt;/p&gt;  &lt;p&gt;Currently, there are several kinds of interlocked operations. In .NET, all interlocked operations are exposed as members of the &lt;a href="http://msdn.microsoft.com/en-us/library/system.threading.interlocked.aspx"&gt;Interlocked&lt;/a&gt; class:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Add: adds two integers (int or long) and replaces the first with the value of the sum; &lt;/li&gt;    &lt;li&gt;CompareAndExchange: compares two values and if they’re equal, replaces one of them with the other (notice that this method receives three parameters). This is probably the most important method of this class (it supports compares and exchanges on reference types two!); &lt;/li&gt;    &lt;li&gt;Decrement: Similar to add, but in this case, it performs a subtraction; &lt;/li&gt;    &lt;li&gt;Exchange: updates a variable with another value; &lt;/li&gt;    &lt;li&gt;Increment: adds one to an existing variable; &lt;/li&gt;    &lt;li&gt;Read: reads a value from a variable; &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;As I’ve said before, the advantage of using these methods is that all the operations are performed atomically. The Read method might not seen necessary at first until you look at its signature:&lt;/p&gt;  &lt;pre style="background-color:black;" class="code"&gt;&lt;span style="color:#ff8000;"&gt;public static long &lt;/span&gt;&lt;span style="color:white;"&gt;Read(&lt;/span&gt;&lt;span style="color:#ff8000;"&gt;ref long &lt;/span&gt;&lt;span style="color:white;"&gt;location);&lt;/span&gt;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;As you can see, it should only be used in 32 bits system when you need to access 64 bits integers. Atomically setting a value on 64 bits can be done through the Exchange method:&lt;/p&gt;

&lt;pre style="background-color:black;" class="code"&gt;&lt;span style="color:#ff8000;"&gt;public static extern long &lt;/span&gt;&lt;span style="color:white;"&gt;Exchange(&lt;/span&gt;&lt;span style="color:#ff8000;"&gt;ref long &lt;/span&gt;&lt;span style="color:white;"&gt;location1, &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;long &lt;/span&gt;&lt;span style="color:white;"&gt;value);&lt;/span&gt;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;This means that you can easily build a generic write or read routine and reuse them across your programs:&lt;/p&gt;

&lt;pre style="background-color:black;" class="code"&gt;&lt;span style="color:#ff8000;"&gt;public static class &lt;/span&gt;&lt;span style="color:yellow;"&gt;Generic64Helper &lt;/span&gt;&lt;span style="color:white;"&gt;{
  &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;private const int &lt;/span&gt;&lt;span style="color:white;"&gt;WordSize32 = 4;
  &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;public static void &lt;/span&gt;&lt;span style="color:white;"&gt;WriteLong(&lt;/span&gt;&lt;span style="color:#ff8000;"&gt;ref long &lt;/span&gt;&lt;span style="color:white;"&gt;location, &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;long &lt;/span&gt;&lt;span style="color:white;"&gt;value) {
    &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;if &lt;/span&gt;&lt;span style="color:white;"&gt;(&lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IntPtr&lt;/span&gt;&lt;span style="color:white;"&gt;.Size == WordSize32) {
        &lt;/span&gt;&lt;span style="color:yellow;"&gt;Interlocked&lt;/span&gt;&lt;span style="color:white;"&gt;.Exchange(&lt;/span&gt;&lt;span style="color:#ff8000;"&gt;ref &lt;/span&gt;&lt;span style="color:white;"&gt;location, value);
    } &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;else &lt;/span&gt;&lt;span style="color:white;"&gt;{
        location = value;
    }
  }
  &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;public static long &lt;/span&gt;&lt;span style="color:white;"&gt;ReadLong(&lt;/span&gt;&lt;span style="color:#ff8000;"&gt;ref long &lt;/span&gt;&lt;span style="color:white;"&gt;location) {
    &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;if &lt;/span&gt;&lt;span style="color:white;"&gt;(&lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IntPtr&lt;/span&gt;&lt;span style="color:white;"&gt;.Size == WordSize32) {
        &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;return &lt;/span&gt;&lt;span style="color:yellow;"&gt;Interlocked&lt;/span&gt;&lt;span style="color:white;"&gt;.Read(&lt;/span&gt;&lt;span style="color:#ff8000;"&gt;ref &lt;/span&gt;&lt;span style="color:white;"&gt;location);
    }
    &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;return &lt;/span&gt;&lt;span style="color:white;"&gt;location;
  }
}&lt;/span&gt;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;There a couple of interesting things going on here. First, we use the &lt;a href="http://msdn.microsoft.com/en-us/library/system.intptr.size.aspx"&gt;IntPtr.Size&lt;/a&gt; property to get the size of the “current” word. In 64 bits, we really don’t want to pay the price of the Interlocked operation and will simply delegate to a hardware atomic write or read. However, in 32 bits system (where the word size is 4), we really need to use those methods to have atomicity. Reusing this class is rather simple, as you can see from the next snippet (t is initialized with 10 and y is initialized with the value of t):&lt;/p&gt;

&lt;pre style="background-color:black;" class="code"&gt;&lt;span style="color:yellow;"&gt;Generic64Helper&lt;/span&gt;&lt;span style="color:white;"&gt;.WriteLong(&lt;/span&gt;&lt;span style="color:#ff8000;"&gt;ref &lt;/span&gt;&lt;span style="color:white;"&gt;t, 10);
&lt;/span&gt;&lt;span style="color:#ff8000;"&gt;long &lt;/span&gt;&lt;span style="color:white;"&gt;y = &lt;/span&gt;&lt;span style="color:yellow;"&gt;Generic64Helper&lt;/span&gt;&lt;span style="color:white;"&gt;.ReadLong(&lt;/span&gt;&lt;span style="color:#ff8000;"&gt;ref &lt;/span&gt;&lt;span style="color:white;"&gt;t);&lt;/span&gt;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;There a couple of gotchas with the previous approach (notice that only the read and write are atomics), but we’ll leave that for a future post. Now, the important thing is to concentrate on introducing most of these methods. If you use reflector, you should see that Interlocked.Read depends directly on the CompareExchange method:&lt;/p&gt;

&lt;pre style="background-color:black;" class="code"&gt;&lt;span style="color:#ff8000;"&gt;public static long &lt;/span&gt;&lt;span style="color:white;"&gt;Read(&lt;/span&gt;&lt;span style="color:#ff8000;"&gt;ref long &lt;/span&gt;&lt;span style="color:white;"&gt;location) {
  &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;return &lt;/span&gt;&lt;span style="color:white;"&gt;CompareExchange(&lt;/span&gt;&lt;span style="color:#ff8000;"&gt;ref &lt;/span&gt;&lt;span style="color:white;"&gt;location, 0L, 0L);
}
&lt;/span&gt;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;This is really a cool trick!&lt;/p&gt;

&lt;p&gt;As I’ve said before, the CompareExchange method is one of the most important methods exposed by the class. The CompareExchange method receives three parameters: if the first and third parameters are equal, then it updates the first with the value of the second parameter. The method will always return the initial value of the first parameter (even when there’s no update).&lt;/p&gt;

&lt;p&gt;So, the code used on the Read method will only end up doing a write (ie, a store) if the current stored value is 0. And even when this happens, there really isn’t any update in the value (notice that if its value is 0 we’re writing 0 again!).&lt;/p&gt;

&lt;p&gt;The remaining methods exposed by the class are fairly obvious, so I won’t really go into examples here (the docs do a good job on showing how to use these methods). The important thing to take from this post is that these operations are atomic and are performed at the hardware level. On the next post, we’ll keep talking about this class and on how you can reuse them to add some free lock programming to your apps. Keep tuned!&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1697571" width="1" height="1"&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/V0VAh9-Xx3O1Hb24QKX-1G7tCms/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/V0VAh9-Xx3O1Hb24QKX-1G7tCms/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/V0VAh9-Xx3O1Hb24QKX-1G7tCms/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/V0VAh9-Xx3O1Hb24QKX-1G7tCms/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;</description><category domain="http://msmvps.com/blogs/luisabreu/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://msmvps.com/blogs/luisabreu/archive/tags/Multithreading/default.aspx">Multithreading</category><feedburner:origLink>http://msmvps.com/blogs/luisabreu/archive/2009/07/02/multithreading-introducing-the-interlocked-operations.aspx</feedburner:origLink></item><item><title>Multithreading: hardware atomicity</title><link>http://feedproxy.google.com/~r/Laneten/~3/VmlGowO3g48/multithreading-hardware-atomicity.aspx</link><pubDate>Mon, 29 Jun 2009 21:41:30 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1697202</guid><dc:creator>luisabreu</dc:creator><slash:comments>0</slash:comments><wfw:commentRss>http://msmvps.com/blogs/luisabreu/rsscomments.aspx?PostID=1697202</wfw:commentRss><comments>http://msmvps.com/blogs/luisabreu/archive/2009/06/29/multithreading-hardware-atomicity.aspx#comments</comments><description>&lt;p&gt;In the previous &lt;a href="http://msmvps.com/blogs/luisabreu/archive/2009/06/29/multithreading-load-and-store-reordering.aspx"&gt;post&lt;/a&gt;, we’ve started looking at memory loads and stores reordering. In this post, we’re going to keep our study and we’re going to introduce atomicity. Atomicity is a really important concept we’ve met in the past. We’ve already talked about it on a higher level: do you recall our discussion on critical regions (and how they’re implemented through critical sections)? &lt;/p&gt;  &lt;p&gt;With critical regions we were able to get atomicity at a high level (though at a logical level – recall that using a critical region you can have a “logical” instruction which is really a group of low level instructions). In this post, we’re really into understanding memory loads and stores and that’s why we’re interested in low level atomicity. At this level, atomic operations are performed as a single instruction between the processor and memory and ensure that a thread never sees a corrupt value. &lt;/p&gt;  &lt;p&gt;Regarding memory access,&amp;#160; &lt;strong&gt;all processors ensure that we have atomic loads and stores of aligned word sized values &lt;/strong&gt;(note that I’m talking about the current processors on which windows can run). &lt;/p&gt;  &lt;p&gt;Since I’m also a beginner, I think that explaining these concepts a&amp;#160; little bit more might be a good idea. Lets start with the concept of word sized values. Word sized values, aka pointer sized values, represent the maximum amount of memory a processor can handle at a time. for instance, on a 32 bits processor, the word sized value is 32 bits, ie, 4 bytes.&amp;#160; On a 64 bit processor, you get an 8 byte word sized value. Notice that we generally use bytes for memory sizes instead of bits. I guess that you’ve got the general idea, right?&lt;/p&gt;  &lt;p&gt;Now, the second part, which is also important: &lt;strong&gt;aligned&lt;/strong&gt;. We say that a value is aligned if its address begins at a position which is evenly divisible by a certain memory unit size. For instance, a value is said to be 4 byte aligned if its memory starts on a position which is evenly divisible by 4. Here’s a practical example: if you’re loading a word sized value which “starts” at 0x28, then you can be sure that you’re accessing a value that can be 4 or 8 byte aligned&amp;#160; (notice that 0x28 = 40 in decimal, which is evenly divisible by 4 or by 8 ).&lt;/p&gt;  &lt;p&gt;Since this is really important, I guess I’ll repeat myself again: &lt;strong&gt;you’ll *only* get atomicity when you load or store an aligned word sized value&lt;/strong&gt;. If you’re loading or storing a value which is smaller than the processor’s word size, you’ll still need to respect the current alignment. For instance, if you’re in&amp;#160; a 32 bit processor, where words are 4 bytes long, then that value should be positioned on a position whose address is divisible by 4 (note that you’ll probably need to&amp;#160; “fill” – relax, this is generally done by the compiler :) -&amp;#160; the other 3 bytes with padding so that the next value is also aligned to ensure proper atomicity). &lt;/p&gt;  &lt;p&gt;On the other hand, if you need more space than is available for the current processor’s word size, then you will not get hardware atomicity for that load or store (and this happens even if the value is aligned). In these cases, you’ll need to watch out because you can’t simply load and store a value without any further consideration. If you do this, then you can end up with a thread loading the value before another has completed storing it! (btw, this is know as torn read)&lt;/p&gt;  &lt;p&gt;(It’s important to understand that this behavior is also observed for chunks of memory smaller&amp;#160; than or equal to the processor’s word size if that value isn’t aligned.)&lt;/p&gt;  &lt;p&gt;For instance, this means that if you’re writing multithreaded code that uses long variables and you’re running that code in 32 bits processors, then you shouldn’t forget to protect those write and read operations ! (in future posts. we’ll talk about interlocked operations; if you’re not using them, then you’ll need at least a lock - but don’t get too smart using a lock for “writing only” because that will not work in all the scenarios).&lt;/p&gt;  &lt;p&gt;Now that we’re clear on alignments and processor’s word sizes, it’s time to take a quick look at how things work in the CLR. The good new is that the C# compiler and the JIT ensure proper alignment in all cases. In practice, values bigger than 4 bytes on 32 bits processors and values bigger that 8 bytes on 64 bits processors always start on 4 or 8 byte aligned boundaries. When we’re working with smaller values, the CLR will also ensure proper placement, filling the remaining space with padding.&lt;/p&gt;  &lt;p&gt;If you want, you can have more control over the way fields are aligned. If you’ve done interop programming, then you’ve surely met the &lt;a href="http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.structlayoutattribute.aspx"&gt;StructLayoutAttribute&lt;/a&gt; class. This class allows you to control the way fields are defined on the layout of a specific type. If you’re thinking about using this feature (for instance, to control the amount of wasted memory), then proceed with care (in fact, think thrice – yes, I learned this word a few days ago and i could hardly wait for using it in a post :) - before going down this path!). It’s that you can easily end up loosing the CLR’s type safety and that means you’ll probably end up getting exceptions from your code at runtime.&lt;/p&gt;  &lt;p&gt;It’s important to understand that whenever you work with values that fall out of the aligned word size value (a non-aligned value or a value bigger than the current word size), the compiler will end up generating multiple instructions. As we’ve seen, these might end up leading to torn reads if you don’t take the necessary precautions.&lt;/p&gt;  &lt;p&gt;Notice that even though stores and loads of aligned word sized values are atomic, they don’t really let us do much. Why? Simply because there are several scenarios where we need&amp;#160; to check a value before updating and this means that we end up with a load followed by a store. In these cases and in order to ensure atomicity, we’re back to locks (interesting: have you ever though on how locks are implemented?)…or maybe not! The truth is that we’ve got a couple of interlocked operations which ensure atomicity and that are perfect for these scenarios. we’ll talk about them in the next posts. Don’t you think that things are getting rather interesting! Keep tuned! &lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1697202" width="1" height="1"&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/ch1lyJ4aPePOG7nihetTg9Zn6sY/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/ch1lyJ4aPePOG7nihetTg9Zn6sY/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/ch1lyJ4aPePOG7nihetTg9Zn6sY/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/ch1lyJ4aPePOG7nihetTg9Zn6sY/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;</description><category domain="http://msmvps.com/blogs/luisabreu/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://msmvps.com/blogs/luisabreu/archive/tags/Multithreading/default.aspx">Multithreading</category><feedburner:origLink>http://msmvps.com/blogs/luisabreu/archive/2009/06/29/multithreading-hardware-atomicity.aspx</feedburner:origLink></item><item><title>Multithreading: load and store reordering</title><link>http://feedproxy.google.com/~r/Laneten/~3/wZrHw_imdPQ/multithreading-load-and-store-reordering.aspx</link><pubDate>Mon, 29 Jun 2009 09:55:28 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1697064</guid><dc:creator>luisabreu</dc:creator><slash:comments>5</slash:comments><wfw:commentRss>http://msmvps.com/blogs/luisabreu/rsscomments.aspx?PostID=1697064</wfw:commentRss><comments>http://msmvps.com/blogs/luisabreu/archive/2009/06/29/multithreading-load-and-store-reordering.aspx#comments</comments><description>&lt;p&gt;Until now, we’ve been busy talking a look at several interesting topics associated with multithreading programming. As we’ve seen, one of the most problematic areas in multithreaded programs is sharing state across multiple threads. As we’ve seen in several posts along this series, we can use a critical regions for ensuring that shared state is accessed by one thread at a time. In other words, using a critical region ensures that access to shared state is serialized leading to correctness of the program. &lt;/p&gt;  &lt;p&gt;One thing that surprises many people is learning that single variables access isn’t always safe. Understanding why leads us to a new concept: memory loads and stores reordering. Even though most of us have grown used to thinking that the program executes precisely in the order we wrote it, that isn’t really guaranteed. Currently, memory operations like loads (ie, accessing a variable) and stores (ie, putting a value into a variable) can be reordered under the optimization “banner”:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;the first “optimization” you might get will be performed by the compiler. Compilers might move, eliminate (or even add) memory loads and stores to the program of your app. However, compilers will always preserve sequential behavior (though its reordering can break multithreaded code);&lt;/li&gt;    &lt;li&gt;processors might also change the way compiled code gets executed. For instance, modern processors tend to use branch prediction to improve the performance of your program. This is just one of the optimizations that may break your code when run in parallel (ie, after adding multithreading to your app).&lt;/li&gt;    &lt;li&gt;caches may give you wrong results too. Most modern processor architectures employ several levels of caches. Some are shared between all processors, while others are processor specific. Caches tend to break the “memory as a big array” vision, leading to effective reorder of loads and stores (at least, this is the perception you get when caching starts breaking your code).&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;After this small introduction, you should be worried about the code you write because it seems like nothing is safe (if even a simple variable access smaller than the “current” processor word size isn’t safe, then what can we do?). Fortunately, there are some guarantees which we can use to write safe multithreaded programs:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;instruction reordering cannot break the sequential evaluation of the code. What this means is that your code should always run safely and correctly if you run it through a single thread (meaning that we only need to worry with reordering when we write multithreaded code);&lt;/li&gt;    &lt;li&gt;data dependency will always be respected. As an example, this means that if you have something like x = 10; y = x; then memory access won’t be reordered (ie, you will never get y=x; x = 10) because there is a data dependency between x and y;&lt;/li&gt;    &lt;li&gt;finally, all platforms conform to a specific memory model which define the rules that are to be followed for memory loads and stores reordering.&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;I guess that the main thing you should take from these points is that what &lt;strong&gt;is run isn’t always what you’ve written&lt;/strong&gt;. On the next post, we’ll keep looking at these issues and see how critical regions help with memory reordering issues. Keep tuned!&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1697064" width="1" height="1"&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/F_LiQOrof5WGkKg0jOyuIeOQQQc/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/F_LiQOrof5WGkKg0jOyuIeOQQQc/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/F_LiQOrof5WGkKg0jOyuIeOQQQc/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/F_LiQOrof5WGkKg0jOyuIeOQQQc/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;</description><category domain="http://msmvps.com/blogs/luisabreu/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://msmvps.com/blogs/luisabreu/archive/tags/Multithreading/default.aspx">Multithreading</category><feedburner:origLink>http://msmvps.com/blogs/luisabreu/archive/2009/06/29/multithreading-load-and-store-reordering.aspx</feedburner:origLink></item><item><title>New toy: bamboo table</title><link>http://feedproxy.google.com/~r/Laneten/~3/XXq33TYZsk0/new-toy-bamboo-table.aspx</link><pubDate>Sun, 28 Jun 2009 22:44:31 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1696978</guid><dc:creator>luisabreu</dc:creator><slash:comments>6</slash:comments><wfw:commentRss>http://msmvps.com/blogs/luisabreu/rsscomments.aspx?PostID=1696978</wfw:commentRss><comments>http://msmvps.com/blogs/luisabreu/archive/2009/06/28/new-toy-bamboo-table.aspx#comments</comments><description>&lt;p&gt;So, I’ve just got a new toy: a wacom &lt;a href="http://www.wacom.com/bambootablet/bamboo.php"&gt;Bamboo table&lt;/a&gt;. This should be fun after getting a nice free app for drawing :) Any thoughts?&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1696978" width="1" height="1"&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/7CGxs-ZnE-uU7KizWv0iBjVTSTI/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/7CGxs-ZnE-uU7KizWv0iBjVTSTI/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/7CGxs-ZnE-uU7KizWv0iBjVTSTI/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/7CGxs-ZnE-uU7KizWv0iBjVTSTI/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;</description><category domain="http://msmvps.com/blogs/luisabreu/archive/tags/Trivia/default.aspx">Trivia</category><feedburner:origLink>http://msmvps.com/blogs/luisabreu/archive/2009/06/28/new-toy-bamboo-table.aspx</feedburner:origLink></item><item><title>It’s official: I’m one year older</title><link>http://feedproxy.google.com/~r/Laneten/~3/NUmFR-BOVNI/it-s-official-i-m-one-year-older.aspx</link><pubDate>Sat, 27 Jun 2009 08:32:11 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1696841</guid><dc:creator>luisabreu</dc:creator><slash:comments>4</slash:comments><wfw:commentRss>http://msmvps.com/blogs/luisabreu/rsscomments.aspx?PostID=1696841</wfw:commentRss><comments>http://msmvps.com/blogs/luisabreu/archive/2009/06/27/it-s-official-i-m-one-year-older.aspx#comments</comments><description>&lt;p&gt;And that means that I’m 33 years old…damn…&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1696841" width="1" height="1"&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/q8r3XXskVUGLdZaKgPXwtfTSnp0/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/q8r3XXskVUGLdZaKgPXwtfTSnp0/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/q8r3XXskVUGLdZaKgPXwtfTSnp0/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/q8r3XXskVUGLdZaKgPXwtfTSnp0/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;</description><category domain="http://msmvps.com/blogs/luisabreu/archive/tags/Trivia/default.aspx">Trivia</category><feedburner:origLink>http://msmvps.com/blogs/luisabreu/archive/2009/06/27/it-s-official-i-m-one-year-older.aspx</feedburner:origLink></item><item><title>PT LINQ book: it’s finally available on local bookstores</title><link>http://feedproxy.google.com/~r/Laneten/~3/Wz4BPCj9cak/pt-linq-book-it-s-finally-available-on-local-bookstores.aspx</link><pubDate>Fri, 26 Jun 2009 20:54:50 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1696817</guid><dc:creator>luisabreu</dc:creator><slash:comments>2</slash:comments><wfw:commentRss>http://msmvps.com/blogs/luisabreu/rsscomments.aspx?PostID=1696817</wfw:commentRss><comments>http://msmvps.com/blogs/luisabreu/archive/2009/06/26/pt-linq-book-it-s-finally-available-on-local-bookstores.aspx#comments</comments><description>&lt;p&gt;And here’s the proof:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://msmvps.com/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/luisabreu.metablogapi/1007.IMAG0281_5F00_031667EE.jpg"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="IMAG0281" border="0" alt="IMAG0281" src="http://msmvps.com/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/luisabreu.metablogapi/2161.IMAG0281_5F00_thumb_5F00_6944C26F.jpg" width="155" height="205" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;If you’re interested, you can get &lt;a href="http://www.fca.pt/cgi-bin/fca_main.cgi/?op=2&amp;amp;isbn=978-972-722-547-7"&gt;more info&lt;/a&gt; on the publisher’s site.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1696817" width="1" height="1"&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/Z5NR3pgRmD7388Afu9mGyV9oIAE/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/Z5NR3pgRmD7388Afu9mGyV9oIAE/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/Z5NR3pgRmD7388Afu9mGyV9oIAE/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/Z5NR3pgRmD7388Afu9mGyV9oIAE/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;</description><category domain="http://msmvps.com/blogs/luisabreu/archive/tags/Trivia/default.aspx">Trivia</category><feedburner:origLink>http://msmvps.com/blogs/luisabreu/archive/2009/06/26/pt-linq-book-it-s-finally-available-on-local-bookstores.aspx</feedburner:origLink></item><item><title>Multithreading: the BackgroundWorker class</title><link>http://feedproxy.google.com/~r/Laneten/~3/j_IFx1iZBdU/multithreading-the-backgroundworker-class.aspx</link><pubDate>Thu, 25 Jun 2009 10:27:34 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1696693</guid><dc:creator>luisabreu</dc:creator><slash:comments>1</slash:comments><wfw:commentRss>http://msmvps.com/blogs/luisabreu/rsscomments.aspx?PostID=1696693</wfw:commentRss><comments>http://msmvps.com/blogs/luisabreu/archive/2009/06/25/multithreading-the-backgroundworker-class.aspx#comments</comments><description>&lt;p&gt;In the last posts of the series, we’ve been looking at many important features related to GUIs and multithreading. Today, we’re going to wrap up this topic with the &lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx"&gt;BackgroundWorker&lt;/a&gt; class. The previous posts are really targeted at library developers. &lt;/p&gt;  &lt;p&gt;The truth is that having to implement the EAP pattern&amp;#160; to have asynchronous behavior is simply too much work. Interact with the SynchronizationContext object to have asynchronous behavior is really too cumbersome and involves too much boilerplate code. &lt;/p&gt;  &lt;p&gt;Wouldn’t it be good if we had a reusable class where we’d simply need to write the code for the asynchronous operation and that would be able to let us know when things are done? The good news is that there’s already a component you can use for that: the &lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx"&gt;BackgroundWorker&lt;/a&gt; class.&lt;/p&gt;  &lt;p&gt;The &lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx"&gt;BackgroundWorker&lt;/a&gt; class can be seen as a helper class which encapsulates all that boilerplate code we’ve seen in previous posts. Here’s the public API of this class:&lt;/p&gt;  &lt;pre style="background-color:black;" class="code"&gt;&lt;span style="color:#ff8000;"&gt;public class &lt;/span&gt;&lt;span style="color:yellow;"&gt;BackgroundWorker &lt;/span&gt;&lt;span style="color:white;"&gt;: &lt;/span&gt;&lt;span style="color:yellow;"&gt;Component &lt;/span&gt;&lt;span style="color:white;"&gt;{
  &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;public event &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;DoWorkEventHandler &lt;/span&gt;&lt;span style="color:white;"&gt;DoWork;        
  &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;public event &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ProgressChangedEventHandler &lt;/span&gt;&lt;span style="color:white;"&gt;ProgressChanged;        
  &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;public event &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;RunWorkerCompletedEventHandler &lt;br /&gt;                                      &lt;/span&gt;&lt;span style="color:white;"&gt;RunWorkerCompleted;
  &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;public &lt;/span&gt;&lt;span style="color:white;"&gt;BackgroundWorker();    
  &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;public void &lt;/span&gt;&lt;span style="color:white;"&gt;CancelAsync();    
  &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;public void &lt;/span&gt;&lt;span style="color:white;"&gt;ReportProgress(&lt;/span&gt;&lt;span style="color:#ff8000;"&gt;int &lt;/span&gt;&lt;span style="color:white;"&gt;percentProgress);
  &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;public void &lt;/span&gt;&lt;span style="color:white;"&gt;ReportProgress(&lt;br /&gt;                   &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;int &lt;/span&gt;&lt;span style="color:white;"&gt;percentProgress, &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;object &lt;/span&gt;&lt;span style="color:white;"&gt;userState);
  &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;public void &lt;/span&gt;&lt;span style="color:white;"&gt;RunWorkerAsync();
  &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;public void &lt;/span&gt;&lt;span style="color:white;"&gt;RunWorkerAsync(&lt;/span&gt;&lt;span style="color:#ff8000;"&gt;object &lt;/span&gt;&lt;span style="color:white;"&gt;argument);    
  &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;public bool &lt;/span&gt;&lt;span style="color:white;"&gt;CancellationPending { &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;get&lt;/span&gt;&lt;span style="color:white;"&gt;; }        
  &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;public bool &lt;/span&gt;&lt;span style="color:white;"&gt;IsBusy { &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;get&lt;/span&gt;&lt;span style="color:white;"&gt;; }
  &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;public bool &lt;/span&gt;&lt;span style="color:white;"&gt;WorkerReportsProgress { &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;get&lt;/span&gt;&lt;span style="color:white;"&gt;; &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;set&lt;/span&gt;&lt;span style="color:white;"&gt;; }
  &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;public bool &lt;/span&gt;&lt;span style="color:white;"&gt;WorkerSupportsCancellation { &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;get&lt;/span&gt;&lt;span style="color:white;"&gt;; &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;set&lt;/span&gt;&lt;span style="color:white;"&gt;; }
}&lt;/span&gt;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;As you can see, this API is really similar to the one we ended up after adding cancellation to the initial EAP implementation. The truth is that you can see this class as a reusable EAP implementation. You’ve got several events used for:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;signaling the start of an asynchronous operation;&lt;/li&gt;

  &lt;li&gt;for reporting progress;&lt;/li&gt;

  &lt;li&gt;for notifying about the completion of an operation.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Asynchronous operations can be started through one of the two overloads of the RunWorkerAsync method.&amp;#160; This method ends up firing the DoWork event on a separated thread. You’re supposed to handle this event and put the code that should be run asynchronously in that method.&lt;/p&gt;

&lt;p&gt;Cancellation is also available through the CancelAsync method. If you recall our previous discussion about the EAP pattern, then you know that this class supports only one asynchronous operation at a time (notice that the CancelAsync does not receive any object parameter). It’s also important to notice that you need to allow cancellations by setting the WorkerSupportsCancellation property to true.&lt;/p&gt;

&lt;p&gt;Reporting is also available: you can use the ReportProgress method for marshalling report information back to the “main thread”. Anyone that is interested in reporting progress should handle the ProgressChanged event. The same observation we’ve made about cancellations is also valid for progress reporting: you need to enable it by setting the WorkerReportsProgress to true.&lt;/p&gt;

&lt;p&gt;As you might expect, all the operations are supported through an internal AsyncOperation instance which is created when you invoke the RunWorkerAsync method. And I guess that’s it. With this post, we’ve ended our quick analysis on GUIs and multithreading. However, there’s still a lot of things to talk about multithreading, so I’ll keep writing about it. Stay tuned for more!&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1696693" width="1" height="1"&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/fu7M9yXBiFFd5nz2nID9zgnq62Q/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/fu7M9yXBiFFd5nz2nID9zgnq62Q/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/fu7M9yXBiFFd5nz2nID9zgnq62Q/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/fu7M9yXBiFFd5nz2nID9zgnq62Q/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;</description><category domain="http://msmvps.com/blogs/luisabreu/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://msmvps.com/blogs/luisabreu/archive/tags/Multithreading/default.aspx">Multithreading</category><feedburner:origLink>http://msmvps.com/blogs/luisabreu/archive/2009/06/25/multithreading-the-backgroundworker-class.aspx</feedburner:origLink></item><item><title>Multithreading: AsyncOperationManager and AsyncOperation helpers</title><link>http://feedproxy.google.com/~r/Laneten/~3/fUIOVIglLkg/multithreading-asyncoperationmanager-and-asyncoperation-helpers.aspx</link><pubDate>Wed, 24 Jun 2009 11:34:12 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1696563</guid><dc:creator>luisabreu</dc:creator><slash:comments>1</slash:comments><wfw:commentRss>http://msmvps.com/blogs/luisabreu/rsscomments.aspx?PostID=1696563</wfw:commentRss><comments>http://msmvps.com/blogs/luisabreu/archive/2009/06/24/multithreading-asyncoperationmanager-and-asyncoperation-helpers.aspx#comments</comments><description>&lt;p&gt;In the &lt;a href="http://msmvps.com/blogs/luisabreu/archive/2009/06/23/multithreading-windows-forms-and-synchronization-contexts.aspx"&gt;last&lt;/a&gt; &lt;a href="http://msmvps.com/blogs/luisabreu/archive/2009/06/23/multithreading-introducing-synchronization-contexts.aspx"&gt;posts&lt;/a&gt;, we’ve taken a look at how synchronization contexts help marshal work across threads. Today we’re going to talk about two classes (which we’ve already met in the past when we &lt;a href="http://msmvps.com/blogs/luisabreu/archive/2009/06/17/multithreading-implementing-the-event-based-pattern.aspx"&gt;implemented&lt;/a&gt; the EAP) that abstract even further the use of synchronization contexts: I’m talking about the &lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.asyncoperationmanager.aspx"&gt;AsyncOperationManager&lt;/a&gt; and AsyncOperation classes. Let’s start with the &lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.asyncoperationmanager.aspx"&gt;AsyncOperationManager&lt;/a&gt; class.&lt;/p&gt;  &lt;p&gt;The &lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.asyncoperationmanager.aspx"&gt;AsyncOperationManager&lt;/a&gt; is a simple helper class with very few lines of code in it, as you can see from the next snippet:&lt;/p&gt;  &lt;pre style="background-color:black;" class="code"&gt;&lt;span style="color:#ff8000;"&gt;public static class &lt;/span&gt;&lt;span style="color:yellow;"&gt;AsyncOperationManager &lt;/span&gt;&lt;span style="color:white;"&gt;{
&lt;/span&gt;&lt;span style="color:#ff8000;"&gt;  public static &lt;/span&gt;&lt;span style="color:yellow;"&gt;AsyncOperation &lt;/span&gt;&lt;span style="color:white;"&gt;CreateOperation(&lt;br /&gt;                          &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;object &lt;/span&gt;&lt;span style="color:white;"&gt;userSuppliedState);
&lt;/span&gt;&lt;span style="color:#ff8000;"&gt;  public static &lt;/span&gt;&lt;span style="color:yellow;"&gt;SynchronizationContext &lt;br /&gt;                     &lt;/span&gt;&lt;span style="color:white;"&gt;SynchronizationContext&lt;/span&gt;&lt;span style="color:white;"&gt; { &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;get&lt;/span&gt;&lt;span style="color:white;"&gt;; &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;set&lt;/span&gt;&lt;span style="color:white;"&gt;; }
}&lt;/span&gt;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;As you can see, this is a static class with only two members. The &lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.asyncoperationmanager.synchronizationcontext.aspx"&gt;SynchronizationContext&lt;/a&gt; property lets you access or set the current SynchronizationContext. The biggest advantage it offers when compared with accessing the synchronization context through the SynchronizationContext.Current property (which we’ve used in the previous &lt;a href="http://msmvps.com/blogs/luisabreu/archive/2009/06/23/multithreading-windows-forms-and-synchronization-contexts.aspx"&gt;post&lt;/a&gt;) is that you’ll always get a valid context (notice the comment in the previous post’s &lt;a href="http://msmvps.com/blogs/luisabreu/archive/2009/06/23/multithreading-windows-forms-and-synchronization-contexts.aspx"&gt;sample&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;The &lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.asyncoperationmanager.createoperation.aspx"&gt;CreateOperation&lt;/a&gt; method is the only way you have to create an instance of the &lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.asyncoperation.aspx"&gt;AsyncOperation&lt;/a&gt; type. Each &lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.asyncoperation.aspx"&gt;AsyncOperation&lt;/a&gt; instance can only track one asynchronous operation. The &lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.asyncoperation.aspx"&gt;AsyncOperation&lt;/a&gt; type exposes the following members:&lt;/p&gt;

&lt;pre style="background-color:black;" class="code"&gt;&lt;span style="color:#ff8000;"&gt;public sealed class &lt;/span&gt;&lt;span style="color:yellow;"&gt;AsyncOperation &lt;/span&gt;&lt;span style="color:white;"&gt;{
&lt;/span&gt;&lt;span style="color:#ff8000;"&gt;  public void &lt;/span&gt;&lt;span style="color:white;"&gt;OperationCompleted();&lt;/span&gt;&lt;span style="color:white;"&gt;
&lt;/span&gt;&lt;span style="color:#ff8000;"&gt;  public void &lt;/span&gt;&lt;span style="color:white;"&gt;Post(&lt;/span&gt;&lt;span style="color:#2b91af;"&gt;SendOrPostCallback &lt;/span&gt;&lt;span style="color:white;"&gt;d, &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;object &lt;/span&gt;&lt;span style="color:white;"&gt;arg);
&lt;/span&gt;&lt;span style="color:#ff8000;"&gt;  public void &lt;/span&gt;&lt;span style="color:white;"&gt;PostOperationCompleted(&lt;br /&gt;     &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;SendOrPostCallback &lt;/span&gt;&lt;span style="color:white;"&gt;d, &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;object &lt;/span&gt;&lt;span style="color:white;"&gt;arg);&lt;/span&gt;&lt;span style="color:white;"&gt;
&lt;/span&gt;&lt;span style="color:#ff8000;"&gt;  public &lt;/span&gt;&lt;span style="color:yellow;"&gt;SynchronizationContext &lt;br /&gt;          &lt;/span&gt;&lt;span style="color:white;"&gt;SynchronizationContext { &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;get&lt;/span&gt;&lt;span style="color:white;"&gt;; }
&lt;/span&gt;&lt;span style="color:#ff8000;"&gt;  public object &lt;/span&gt;&lt;span style="color:white;"&gt;UserSuppliedState { &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;get&lt;/span&gt;&lt;span style="color:white;"&gt;; }
}&lt;/span&gt;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;A couple of observations about the previous methods exposed by the &lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.asyncoperation.aspx"&gt;AsyncOperation&lt;/a&gt; type:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;you can access the current synchronization context through the SynchronizationContext property;&lt;/li&gt;

  &lt;li&gt;the UserSuppliedState property lets you access the optional state parameter that you’ve passed through the userSuppliedState parameter (AsyncOperationManager.CreateOperation method);&lt;/li&gt;

  &lt;li&gt;you’re supposed to use the Post operation to marshal a notification back to the “main” thread;&lt;/li&gt;

  &lt;li&gt;you’re supposed to signal the end of the asynchronous operation by calling the PostOperationCompleted method.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;As you can see, the AsyncOperation will always perform the operation in asynchronous fashion (ie, it will always invoke the Post method of the internal SynchronizationContext). The main difference between Post and PostOperationCompleted resides in an internal flag that is set by the 2nd method. After this flag is set, all invocations of the Post/PostOperationCompleted methods end up throwing exceptions.&lt;/p&gt;

&lt;p&gt;By now, I’m thinking that you’ve got enough information for understanding the use of these types when we saw how to &lt;a href="http://msmvps.com/blogs/luisabreu/archive/2009/06/17/multithreading-implementing-the-event-based-pattern.aspx"&gt;implement&lt;/a&gt; the EAP pattern in a previous post, so I’m not going to waste your time repeating what has been said before.&lt;/p&gt;

&lt;p&gt;And that’s all. With this post, I guess that there’s only one thing to talk about: the BackgroundWorker class. We’ll leave that topic for the next post. Keep tuned for more.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1696563" width="1" height="1"&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/t6Ft3ZOh_b3b_is2TZGPyQe_puo/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/t6Ft3ZOh_b3b_is2TZGPyQe_puo/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/t6Ft3ZOh_b3b_is2TZGPyQe_puo/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/t6Ft3ZOh_b3b_is2TZGPyQe_puo/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;</description><category domain="http://msmvps.com/blogs/luisabreu/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://msmvps.com/blogs/luisabreu/archive/tags/Multithreading/default.aspx">Multithreading</category><feedburner:origLink>http://msmvps.com/blogs/luisabreu/archive/2009/06/24/multithreading-asyncoperationmanager-and-asyncoperation-helpers.aspx</feedburner:origLink></item><item><title>Eric Lippert on C# “top methods”</title><link>http://feedproxy.google.com/~r/Laneten/~3/IHVvfzq582c/eric-lippert-on-c-top-methods.aspx</link><pubDate>Tue, 23 Jun 2009 13:33:44 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1696375</guid><dc:creator>luisabreu</dc:creator><slash:comments>0</slash:comments><wfw:commentRss>http://msmvps.com/blogs/luisabreu/rsscomments.aspx?PostID=1696375</wfw:commentRss><comments>http://msmvps.com/blogs/luisabreu/archive/2009/06/23/eric-lippert-on-c-top-methods.aspx#comments</comments><description>&lt;p&gt;Another interesting &lt;a href="http://blogs.msdn.com/ericlippert/archive/2009/06/22/why-doesn-t-c-implement-top-level-methods.aspx"&gt;post&lt;/a&gt; by the great &lt;a href="http://blogs.msdn.com/ericlippert/"&gt;Eric Lippert&lt;/a&gt;.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1696375" width="1" height="1"&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/pFPQ1I68zIMKAx12C4ozJ-3in7Q/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/pFPQ1I68zIMKAx12C4ozJ-3in7Q/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/pFPQ1I68zIMKAx12C4ozJ-3in7Q/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/pFPQ1I68zIMKAx12C4ozJ-3in7Q/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;</description><category domain="http://msmvps.com/blogs/luisabreu/archive/tags/C_2300_/default.aspx">C#</category><feedburner:origLink>http://msmvps.com/blogs/luisabreu/archive/2009/06/23/eric-lippert-on-c-top-methods.aspx</feedburner:origLink></item><item><title>Multithreading: windows forms and synchronization contexts</title><link>http://feedproxy.google.com/~r/Laneten/~3/BMjOENNI4pI/multithreading-windows-forms-and-synchronization-contexts.aspx</link><pubDate>Tue, 23 Jun 2009 11:14:07 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1696356</guid><dc:creator>luisabreu</dc:creator><slash:comments>3</slash:comments><wfw:commentRss>http://msmvps.com/blogs/luisabreu/rsscomments.aspx?PostID=1696356</wfw:commentRss><comments>http://msmvps.com/blogs/luisabreu/archive/2009/06/23/multithreading-windows-forms-and-synchronization-contexts.aspx#comments</comments><description>&lt;p&gt;In the previous &lt;a href="http://msmvps.com/blogs/luisabreu/archive/2009/06/23/multithreading-introducing-synchronization-contexts.aspx"&gt;post&lt;/a&gt;, we’ve started looking at synchronization contexts. In this post, we’ll take a close look at the widows forms custom synchronization context. Whenever you run a windows form app, you might end up interacting with the &lt;a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.windowsformssynchronizationcontext.aspx"&gt;WindowsFormsSynchronizationContext&lt;/a&gt;. The constructor of this class is responsible for getting a reference to the GUI thread so that it can then create a control which will be used for marshalling the results back to the UI thread.&lt;/p&gt;  &lt;p&gt;With a valid reference to a control and after understanding how work is marshaled back to the GUI thread (which involves posting win32 messages to the UI thread – as we’ve seen in this &lt;a href="http://msmvps.com/blogs/luisabreu/archive/2009/06/22/multithreading-the-isynchronizeinvoke-interface.aspx"&gt;post&lt;/a&gt;), it shouldn’t be a surprise to learn that the Post and Send methods are overridden and that the new implementation relies on the BeginInvoke and Invoke methods of the special “marshal” control. Here’s the current implementation copied from reflector:&lt;/p&gt;  &lt;pre style="background-color:black;" class="code"&gt;&lt;span style="color:#ff8000;"&gt;public override void &lt;/span&gt;&lt;span style="color:white;"&gt;Post(&lt;br /&gt;        SendOrPostCallback d, &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;object &lt;/span&gt;&lt;span style="color:white;"&gt;state) {
  &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;if &lt;/span&gt;&lt;span style="color:white;"&gt;(&lt;/span&gt;&lt;span style="color:#ff8000;"&gt;this&lt;/span&gt;&lt;span style="color:white;"&gt;.controlToSendTo != &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;null&lt;/span&gt;&lt;span style="color:white;"&gt;) {
     &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;this&lt;/span&gt;&lt;span style="color:white;"&gt;.controlToSendTo.BeginInvoke(
                d, &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;new object&lt;/span&gt;&lt;span style="color:white;"&gt;[] { state });
  }
}
&lt;/span&gt;&lt;span style="color:#ff8000;"&gt;public override void &lt;/span&gt;&lt;span style="color:white;"&gt;Send(&lt;br /&gt;          SendOrPostCallback d, &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;object &lt;/span&gt;&lt;span style="color:white;"&gt;state) {
  Thread destinationThread = &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;this&lt;/span&gt;&lt;span style="color:white;"&gt;.DestinationThread;
  &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;if &lt;/span&gt;&lt;span style="color:white;"&gt;((destinationThread == &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;null&lt;/span&gt;&lt;span style="color:white;"&gt;) || &lt;br /&gt;      !destinationThread.IsAlive) {
        &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;throw new &lt;/span&gt;&lt;span style="color:white;"&gt;InvalidAsynchronousStateException(&lt;br /&gt;                    SR.GetString(&lt;/span&gt;&lt;span style="color:lime;"&gt;&amp;quot;ThreadNoLongerValid&amp;quot;&lt;/span&gt;&lt;span style="color:white;"&gt;));
  }
  &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;if &lt;/span&gt;&lt;span style="color:white;"&gt;(&lt;/span&gt;&lt;span style="color:#ff8000;"&gt;this&lt;/span&gt;&lt;span style="color:white;"&gt;.controlToSendTo != &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;null&lt;/span&gt;&lt;span style="color:white;"&gt;) {
    &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;this&lt;/span&gt;&lt;span style="color:white;"&gt;.controlToSendTo.Invoke(d, &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;new object&lt;/span&gt;&lt;span style="color:white;"&gt;[] { state });
  }
}&lt;/span&gt;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;As you can see, the implementation performs several auxiliary verifications to ensure that everything is still ok before going on with the invocation of the methods.&lt;/p&gt;

&lt;p&gt;You might be wondering how things get hooked up, ie, how is the &lt;a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.windowsformssynchronizationcontext.aspx"&gt;WindowsFormsSyncrhonizationContext&lt;/a&gt; set up in the current thread’s ExecutionContext. The answer is rather simple: the base Control class performs that task from its constructor, ensuring that whenever you create any window, you end up with the correct synchronization context.&lt;/p&gt;

&lt;p&gt;So, how can we use this information for building multithreaded code for GUIs? The first thing you should do is base your code in synchronization contexts. This ensures that you get the correct behavior and don’t need to worry about GUI threads (notice that this should work in other custom environments that have their own custom synchronization contexts). To show you how you can use this class in code, we’re going to update the code of one of the &lt;a href="http://msmvps.com/blogs/luisabreu/archive/2009/06/22/multithreading-the-isynchronizeinvoke-interface.aspx"&gt;previous&lt;/a&gt; posts so that it uses synchronization contexts instead of relying in a control to marshal work back into the GUI thread:&lt;/p&gt;

&lt;pre style="background-color:black;" class="code"&gt;&lt;span style="color:#ff8000;"&gt;var &lt;/span&gt;&lt;span style="color:white;"&gt;number = GetNumberFromSomewhere();
button1.Enabled = &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;false&lt;/span&gt;&lt;span style="color:white;"&gt;;
&lt;/span&gt;&lt;span style="color:lime;"&gt;//should check for null here!
&lt;/span&gt;&lt;span style="color:#ff8000;"&gt;var &lt;/span&gt;&lt;span style="color:white;"&gt;syncContext = &lt;/span&gt;&lt;span style="color:yellow;"&gt;SynchronizationContext&lt;/span&gt;&lt;span style="color:white;"&gt;.Current;
&lt;/span&gt;&lt;span style="color:yellow;"&gt;ThreadPool&lt;/span&gt;&lt;span style="color:white;"&gt;.QueueUserWorkItem(state =&amp;gt; {
  &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;var &lt;/span&gt;&lt;span style="color:white;"&gt;ctx = state &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;as &lt;/span&gt;&lt;span style="color:yellow;"&gt;SynchronizationContext&lt;/span&gt;&lt;span style="color:white;"&gt;;&lt;br /&gt;  ctx.OperationStarted();
  &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;var &lt;/span&gt;&lt;span style="color:white;"&gt;isPrime = &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;false&lt;/span&gt;&lt;span style="color:white;"&gt;;
  &lt;/span&gt;&lt;span style="color:yellow;"&gt;Exception &lt;/span&gt;&lt;span style="color:white;"&gt;thrownException = &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;null&lt;/span&gt;&lt;span style="color:white;"&gt;;
  &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;try &lt;/span&gt;&lt;span style="color:white;"&gt;{
    //algorithm for checking if number is prime&lt;br /&gt;&lt;/span&gt;&lt;span style="color:white;"&gt;  } &lt;br /&gt;  &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;catch &lt;/span&gt;&lt;span style="color:white;"&gt;(&lt;/span&gt;&lt;span style="color:yellow;"&gt;Exception &lt;/span&gt;&lt;span style="color:white;"&gt;ex) {
    thrownException = ex;
  } 
  &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;finally &lt;/span&gt;&lt;span style="color:white;"&gt;{
    ctx.Send(marshaledState =&amp;gt; {
      &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;var &lt;/span&gt;&lt;span style="color:white;"&gt;result = marshaledState &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;as &lt;/span&gt;&lt;span style="color:yellow;"&gt;PrimeVerifierResult&lt;/span&gt;&lt;span style="color:white;"&gt;;
      button1.Enabled = &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;true&lt;/span&gt;&lt;span style="color:white;"&gt;;
      &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;if &lt;/span&gt;&lt;span style="color:white;"&gt;(result.ThrownException != &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;null&lt;/span&gt;&lt;span style="color:white;"&gt;) {
                &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;throw &lt;/span&gt;&lt;span style="color:white;"&gt;result.ThrownException;
      }
      &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;if &lt;/span&gt;&lt;span style="color:white;"&gt;(result.IsPrime) {
        &lt;/span&gt;&lt;span style="color:yellow;"&gt;MessageBox&lt;/span&gt;&lt;span style="color:white;"&gt;.Show(&lt;/span&gt;&lt;span style="color:lime;"&gt;&amp;quot;Prime number&amp;quot;&lt;/span&gt;&lt;span style="color:white;"&gt;);
      }
   },
   &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;new &lt;/span&gt;&lt;span style="color:yellow;"&gt;PrimeVerifierResult&lt;/span&gt;&lt;span style="color:white;"&gt;(isPrime, thrownException));&lt;br /&gt;   ctx.OperationCompleted();
&lt;br /&gt; }        
},
syncContext);&lt;/span&gt;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;A couple of observations on the previous snippet:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;you should always check the context obtained from the Current property (though that is not done in this snippet);&lt;/li&gt;

  &lt;li&gt;updating the button’s state needs to be done from the GUI thread. This is a peace of cake because we’ve already got a reference to the current SynchronizationContext (obtained on the GUI thread and passed to the secondary thread through the state parameter) and the only thing we need to do is call Send or Post;&lt;/li&gt;

  &lt;li&gt;notice how we signal the beginning and ending of an operation by calling the OperationStarted and OperationCompleted methods. This allows us to notify the synchronous context that an asynchronous operation began&amp;#160; so that it can perform any operation it sees fit.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Looking at the previous sample, you might think that it’s not as simple as the &lt;a href="http://msmvps.com/blogs/luisabreu/archive/2009/06/22/multithreading-the-isynchronizeinvoke-interface.aspx"&gt;first&lt;/a&gt; one. And you’re right: if I was writing this code, I’d always go with &lt;a href="http://msmvps.com/blogs/luisabreu/archive/2009/06/22/multithreading-the-isynchronizeinvoke-interface.aspx"&gt;option 1&lt;/a&gt;. &lt;/p&gt;

&lt;p&gt;If instead of putting this code on the GUI, I told you that you’d need to write a a class that could be reused across several GUIs, then you can probably start seeing value in the previous code. In fact, if&amp;#160; you look at it and pay enough attention, you can start to see that it looks a lot like the code we had when we implemented the &lt;a href="http://msmvps.com/blogs/luisabreu/archive/2009/06/17/multithreading-implementing-the-event-based-pattern.aspx"&gt;EAP pattern&lt;/a&gt;: the main difference is that his code relies on a SynchronousContext instance while that old code used the AsyncOperation and AsyncOperationManager classes (btw, I’m talking about the internals here!).&lt;/p&gt;

&lt;p&gt;The truth is that these classes are just helpers and in the next post we’ll see how they relate with synchronization contexts. Until then, stay tuned! &lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1696356" width="1" height="1"&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/gUr0XCy6VPpUzW8I60YvQ0jMs1c/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/gUr0XCy6VPpUzW8I60YvQ0jMs1c/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/gUr0XCy6VPpUzW8I60YvQ0jMs1c/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/gUr0XCy6VPpUzW8I60YvQ0jMs1c/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;</description><category domain="http://msmvps.com/blogs/luisabreu/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://msmvps.com/blogs/luisabreu/archive/tags/Multithreading/default.aspx">Multithreading</category><feedburner:origLink>http://msmvps.com/blogs/luisabreu/archive/2009/06/23/multithreading-windows-forms-and-synchronization-contexts.aspx</feedburner:origLink></item><item><title>Multithreading: Introducing synchronization contexts</title><link>http://feedproxy.google.com/~r/Laneten/~3/6PslrEflfXE/multithreading-introducing-synchronization-contexts.aspx</link><pubDate>Tue, 23 Jun 2009 10:08:22 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1696347</guid><dc:creator>luisabreu</dc:creator><slash:comments>3</slash:comments><wfw:commentRss>http://msmvps.com/blogs/luisabreu/rsscomments.aspx?PostID=1696347</wfw:commentRss><comments>http://msmvps.com/blogs/luisabreu/archive/2009/06/23/multithreading-introducing-synchronization-contexts.aspx#comments</comments><description>&lt;p&gt;In the last &lt;a href="http://msmvps.com/blogs/luisabreu/archive/2009/06/22/multithreading-the-isynchronizeinvoke-interface.aspx"&gt;post&lt;/a&gt;, we’ve seen how to marshal back the results obtained on a secondary thread so that controls are updated on the GUI thread. Today we’re going to start looking at synchronization contexts. Synchronization contexts are abstractions for marshalling between threads. In other words, they abstract those scenarios where you cannot call a method from the current thread and need to make sure that the method is executed on a specific thread (as we’ve seen, GUIs fall in this kind of scenario).&lt;/p&gt;  &lt;p&gt;As we’ve seen in the previous &lt;a href="http://msmvps.com/blogs/luisabreu/archive/2009/06/22/multithreading-the-isynchronizeinvoke-interface.aspx"&gt;example&lt;/a&gt;, GUI controls can only be updated from the GUI thread and in that &lt;a href="http://msmvps.com/blogs/luisabreu/archive/2009/06/22/multithreading-the-isynchronizeinvoke-interface.aspx"&gt;example&lt;/a&gt;, we’ve relied on the &lt;a href="http://msdn.microsoft.com/pt-br/library/system.componentmodel.isynchronizeinvoke(VS.80).aspx"&gt;ISynchronizeInvoke&lt;/a&gt; method for running the code on the correct thread. In practice, whenever we’ve got a reference to a control, we can use its Invoke or BeginInvoke method to marshal work back to the current thread. The problem is getting a reference to the control. When we build the form, this is simple because we know the controls that are placed on the form and it is easy to get a reference to any of them.&lt;/p&gt;  &lt;p&gt;However, suppose we’re building a general component that needs to be reused on several GUI apps. Now things become harder and we’d need to write boilerplate code for getting a control so that we can marshal work back into the GUI thread. This is where synchronization contexts step in and save the day. Before delving into the specifics of the synchronization contexts used on GUIs, lets take a step back an study the general API introduced by the base SynchronizationContext class:&lt;/p&gt;  &lt;pre style="background-color:black;" class="code"&gt;&lt;span style="color:#ff8000;"&gt;public class &lt;/span&gt;&lt;span style="color:yellow;"&gt;SynchronizationContext &lt;/span&gt;&lt;span style="color:white;"&gt;{
  &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;public virtual &lt;/span&gt;&lt;span style="color:yellow;"&gt;SynchronizationContext &lt;/span&gt;&lt;span style="color:white;"&gt;CreateCopy();    
  &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;public bool &lt;/span&gt;&lt;span style="color:white;"&gt;IsWaitNotificationRequired();
  &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;public virtual void &lt;/span&gt;&lt;span style="color:white;"&gt;OperationCompleted();
  &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;public virtual void &lt;/span&gt;&lt;span style="color:white;"&gt;OperationStarted();
  &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;public virtual void &lt;/span&gt;&lt;span style="color:white;"&gt;Post(&lt;/span&gt;&lt;span style="color:#2b91af;"&gt;SendOrPostCallback &lt;/span&gt;&lt;span style="color:white;"&gt;d, &lt;br /&gt;                               &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;object &lt;/span&gt;&lt;span style="color:white;"&gt;state);
  &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;public virtual void &lt;/span&gt;&lt;span style="color:white;"&gt;Send(&lt;/span&gt;&lt;span style="color:#2b91af;"&gt;SendOrPostCallback &lt;/span&gt;&lt;span style="color:white;"&gt;d, &lt;br /&gt;                             &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;object &lt;/span&gt;&lt;span style="color:white;"&gt;state);    

  &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;public virtual int &lt;/span&gt;&lt;span style="color:white;"&gt;Wait(&lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IntPtr&lt;/span&gt;&lt;span style="color:white;"&gt;[] waitHandles, &lt;br /&gt;                            &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;bool &lt;/span&gt;&lt;span style="color:white;"&gt;waitAll, &lt;br /&gt;                            &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;int &lt;/span&gt;&lt;span style="color:white;"&gt;millisecondsTimeout);

  &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;public static &lt;/span&gt;&lt;span style="color:yellow;"&gt;SynchronizationContext &lt;/span&gt;&lt;span style="color:white;"&gt;Current { &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;get&lt;/span&gt;&lt;span style="color:white;"&gt;; }
  &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;public static void &lt;/span&gt;&lt;span style="color:white;"&gt;SetSynchronizationContext(&lt;br /&gt;                     &lt;/span&gt;&lt;span style="color:yellow;"&gt;SynchronizationContext &lt;/span&gt;&lt;span style="color:white;"&gt;syncContext);
}&lt;/span&gt;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;As you can see, you can get (Current property) or set (by calling the static SetSynchronizationContext) a thread’s synchronization context. Synchronization contexts are always obtained through the “current” ExecutionContext (which you can get through the ExecutionContext property of the thread class). Notice that if you want to interact with synchronization contests, you must be prepared for getting a null reference.&lt;/p&gt;

&lt;p&gt;Even though a synchronization context is part of the ExecutionContext, it’s important to keep in mind that queuing an item on the thread pool will never propagate the “current” SynchronizationContext (not even when you use the QueueUserWorkItem method – event though the execution context is propagated, the synchronization context is one of the items that will not be propagated to the new thread).&lt;/p&gt;

&lt;p&gt;Post and Send are probably the most important methods exposed by the class. As you can see, both expect a SendOrPostDelegate and an option object parameter for passing some state to that delegate. The difference is that Post performs the operation in asynchronous fashion while Send performs a synchronous callback. The default implementation of these methods is rather simple: Post uses the thread pool while send simply invokes the delegate.&lt;/p&gt;

&lt;p&gt;The OperationStarted and OperationCompleted methods let you receive notifications when an operation starts and ends. The default SynchronizationContext doesn’t do anything in these methods, but as we’ll see, they can be used for (for example) tracking running operations. &lt;/p&gt;

&lt;p&gt;Finally, we’ve got a Wait method. The CLR uses this method for waiting if you the IsWaitNotificationRequired property is set to true. What this means is that whenever you wait on a thread that has a synchronization context that has this property set to true, your wait calls end up being redirected to this Wait method. Custom synchronization contexts override this method to perform some specific actions whenever a thread needs to wait on a specific action.&lt;/p&gt;

&lt;p&gt;And that’s it. After this brief introduction, we’re ready to take a look at the synchronization contexts used by windows forms. But we’ll leave that to the next post. Keep tuned!&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1696347" width="1" height="1"&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/u9uxkLa7zAoQIuz7ZAOcVq-ZY3Q/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/u9uxkLa7zAoQIuz7ZAOcVq-ZY3Q/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/u9uxkLa7zAoQIuz7ZAOcVq-ZY3Q/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/u9uxkLa7zAoQIuz7ZAOcVq-ZY3Q/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;</description><category domain="http://msmvps.com/blogs/luisabreu/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://msmvps.com/blogs/luisabreu/archive/tags/Multithreading/default.aspx">Multithreading</category><feedburner:origLink>http://msmvps.com/blogs/luisabreu/archive/2009/06/23/multithreading-introducing-synchronization-contexts.aspx</feedburner:origLink></item><item><title>Multithreading: the ISynchronizeInvoke interface</title><link>http://feedproxy.google.com/~r/Laneten/~3/fhrBPVA5XjE/multithreading-the-isynchronizeinvoke-interface.aspx</link><pubDate>Mon, 22 Jun 2009 19:26:37 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1696230</guid><dc:creator>luisabreu</dc:creator><slash:comments>2</slash:comments><wfw:commentRss>http://msmvps.com/blogs/luisabreu/rsscomments.aspx?PostID=1696230</wfw:commentRss><comments>http://msmvps.com/blogs/luisabreu/archive/2009/06/22/multithreading-the-isynchronizeinvoke-interface.aspx#comments</comments><description>&lt;p&gt;In the last post, we’ve see that multithreading is almost a necessity in GUIs. We’ve also seen that there are some gotchas associated with it: a control can only be updated from the GUI thread. In practice, this means that we’ll need to marshal back the results to the main thread when they’re ready.&lt;/p&gt;  &lt;p&gt;In .NET, the Windows Forms introduces the ISynchronizeInvoke interface for performing that kind of operation:&lt;/p&gt;  &lt;pre style="background-color:black;" class="code"&gt;&lt;span style="color:#ff8000;"&gt;public interface &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ISynchronizeInvoke &lt;/span&gt;&lt;span style="color:white;"&gt;{
  &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IAsyncResult &lt;/span&gt;&lt;span style="color:white;"&gt;BeginInvoke(&lt;/span&gt;&lt;span style="color:yellow;"&gt;Delegate &lt;/span&gt;&lt;span style="color:white;"&gt;method, &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;object&lt;/span&gt;&lt;span style="color:white;"&gt;[] args);
  &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;object &lt;/span&gt;&lt;span style="color:white;"&gt;EndInvoke(&lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IAsyncResult &lt;/span&gt;&lt;span style="color:white;"&gt;result);
  &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;object &lt;/span&gt;&lt;span style="color:white;"&gt;Invoke(&lt;/span&gt;&lt;span style="color:yellow;"&gt;Delegate &lt;/span&gt;&lt;span style="color:white;"&gt;method, &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;object&lt;/span&gt;&lt;span style="color:white;"&gt;[] args);
  &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;bool &lt;/span&gt;&lt;span style="color:white;"&gt;InvokeRequired { &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;get&lt;/span&gt;&lt;span style="color:white;"&gt;; }
}&lt;/span&gt;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;The Control class (which is reused by all the existing controls) implements this interface, letting you marshal the results back to the main thread by calling one of the Invoke methods.&lt;/p&gt;

&lt;p&gt;As you can see from the interface API, you can block the secondary thread until the GUI is updated (in this case, you use the Invoke method, which is equivalent to calling BeginInvoke followed by EndInvoke), or you can perform that work in asynchronous fashion, by invoking the BeginInvoke method and use one of the available approaches for waiting on the IAsyncResult returned. Besides these methods, the Control class offers two extra helper methods which you can use when you don’t need to pass parameters to the delegate:&lt;/p&gt;

&lt;pre style="background-color:black;" class="code"&gt;&lt;span style="color:#ff8000;"&gt;public &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IAsyncResult &lt;/span&gt;&lt;span style="color:white;"&gt;BeginInvoke(&lt;/span&gt;&lt;span style="color:yellow;"&gt;Delegate &lt;/span&gt;&lt;span style="color:white;"&gt;method);
&lt;/span&gt;&lt;span style="color:#ff8000;"&gt;public object &lt;/span&gt;&lt;span style="color:white;"&gt;Invoke(&lt;/span&gt;&lt;span style="color:yellow;"&gt;Delegate &lt;/span&gt;&lt;span style="color:white;"&gt;method);&lt;/span&gt;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;These are just shortcuts to the previous methods and don’t offer any benefits over the interface methods.&lt;/p&gt;

&lt;p&gt;The InvokeRequired property is there for checking if marshalling is needed. After all, you don’t want to marshal if you don’t have to, right? Checking if marshalling is needed involves getting the Win32 control’s handle and seeing its window’s thread is the same as the current one.&lt;/p&gt;

&lt;p&gt;Internally, the control class performs several interesting steps for executing the update on GUI through the Invoke methods(sync or async):&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;it starts by getting a reference to the control (or parent control) which has an associated Win32 handle; &lt;/li&gt;

  &lt;li&gt;it checks the associated thread ID (the unmanaged thread ID) and sees if marshaling will be needed (this happens whenever the control’s windows thread is different from the current thread that is calling the Invoke method – this relies in using the &lt;a href="http://msdn.microsoft.com/en-us/library/ms633522.aspx"&gt;GetWindowThreadProcessId&lt;/a&gt; win 32 function; &lt;/li&gt;

  &lt;li&gt;it propagates the current ExecutionContext (more on this in future posts) so that it flows across threads; &lt;/li&gt;

  &lt;li&gt;if needed, it posts a message by using the Win32 &lt;a href="http://msdn.microsoft.com/en-us/library/ms644944(VS.85).aspx"&gt;PostMessage&lt;/a&gt; method (that’s why it needs to get a reference to a control that has a Win32 handle) and sets up a callback that will be fired when the message is processed. &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;As you’d expect, there’s a custom IAsyncResult implementation which performs many of the things we’ve seen before (like allocating a lazy event so that it is created only if it’s needed, etc, etc). To show you how easy it is to use marshalling, we’re going to create a Windows Forms test project which will use a secondary thread for calculating if a number is prime. We’ll start with a really simple form which has only one button for starting the operation:&lt;/p&gt;

&lt;p&gt;&lt;a href="http://msmvps.com/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/luisabreu.metablogapi/7848.frm_5F00_4450C265.jpg"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="frm" border="0" alt="frm" src="http://msmvps.com/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/luisabreu.metablogapi/7455.frm_5F00_thumb_5F00_35A8A731.jpg" width="162" height="117" /&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;Here’s the code we’ve added to the buttons click event:&lt;/p&gt;

&lt;pre style="background-color:black;" class="code"&gt;&lt;span style="color:#ff8000;"&gt;private void &lt;/span&gt;&lt;span style="color:white;"&gt;button1_Click(&lt;/span&gt;&lt;span style="color:#ff8000;"&gt;object &lt;/span&gt;&lt;span style="color:white;"&gt;sender, &lt;/span&gt;&lt;span style="color:yellow;"&gt;EventArgs &lt;/span&gt;&lt;span style="color:white;"&gt;e) {
  button1.Enabled = &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;false&lt;/span&gt;&lt;span style="color:white;"&gt;;
  &lt;/span&gt;&lt;span style="color:yellow;"&gt;ThreadPool&lt;/span&gt;&lt;span style="color:white;"&gt;.UnsafeQueueUserWorkItem(state =&amp;gt;
  {
    &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;var &lt;/span&gt;&lt;span style="color:white;"&gt;isPrime = CheckIfNumberIsPrime((&lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Int32&lt;/span&gt;&lt;span style="color:white;"&gt;)state);
    &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Action &lt;/span&gt;&lt;span style="color:white;"&gt;updater = () =&amp;gt; { &lt;br /&gt;                 &lt;/span&gt;&lt;span style="color:yellow;"&gt;MessageBox&lt;/span&gt;&lt;span style="color:white;"&gt;.Show(isPrime.ToString());&lt;br /&gt;                 button1.Enabled = true;   };
    button1.Invoke(updater, &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;null&lt;/span&gt;&lt;span style="color:white;"&gt;);
  },
  19&lt;/span&gt;&lt;span style="color:lime;"&gt;// hardcoded number
  &lt;/span&gt;&lt;span style="color:white;"&gt;);
}&lt;/span&gt;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;As you can see, we’re making sure that all UI code runs on the GUI thread. The important thing here is making sure that the Enable property is set from the correct thread. In pre-NET 2.0, you could go ahead and set a property from a secondary thread. Most of the time, things would work and you’d get occasional crashes which were difficult to debug. From .NET 2.0 onward, the behavior changed: when you’re running in a debugger, you’ll always get additional checks which verify if the code is being called from the correct thread.&lt;/p&gt;

&lt;p&gt;As a final optimization, you’ll probably want to stop the ExecutionContext from flowing in most GUI apps (specially for full trust apps). Doing this is as simple as calling the SuppressFlow method:&lt;/p&gt;

&lt;pre style="background-color:black;" class="code"&gt;&lt;span style="color:yellow;"&gt;ExecutionContext&lt;/span&gt;&lt;span style="color:white;"&gt;.SuppressFlow();&lt;/span&gt;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;And that’s it for today. Keep tuned for more on multithreading.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1696230" width="1" height="1"&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/JEqX7mIBEYXmYFc9tOdSQS43Ie0/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/JEqX7mIBEYXmYFc9tOdSQS43Ie0/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/JEqX7mIBEYXmYFc9tOdSQS43Ie0/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/JEqX7mIBEYXmYFc9tOdSQS43Ie0/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;</description><category domain="http://msmvps.com/blogs/luisabreu/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://msmvps.com/blogs/luisabreu/archive/tags/Multithreading/default.aspx">Multithreading</category><feedburner:origLink>http://msmvps.com/blogs/luisabreu/archive/2009/06/22/multithreading-the-isynchronizeinvoke-interface.aspx</feedburner:origLink></item><item><title>Multithreading: why multithreading on GUIs</title><link>http://feedproxy.google.com/~r/Laneten/~3/l4V1yuIPDrw/multithreading-why-multithreading-on-guis.aspx</link><pubDate>Sun, 21 Jun 2009 12:52:17 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1696012</guid><dc:creator>luisabreu</dc:creator><slash:comments>0</slash:comments><wfw:commentRss>http://msmvps.com/blogs/luisabreu/rsscomments.aspx?PostID=1696012</wfw:commentRss><comments>http://msmvps.com/blogs/luisabreu/archive/2009/06/21/multithreading-why-multithreading-on-guis.aspx#comments</comments><description>&lt;p&gt;In the latest posts, we’ve seen how to implement the event based asynchronous (EAP). When we introduced at the main features of the EAP, I’ve said that you should use this pattern when the consumers of your classes are GUIs programmers.&lt;/p&gt;  &lt;p&gt;Since we’ve already learned lots of things about EAP, now it’s probably a good time for starting to look at asynchronous programming and GUIs. GUIs are probably one of the areas which will get the most from multithreading. To understand why, we need to make a small detour on how GUIs work in windows. Since I’m focusing on managed code, from now on I’ll be using windows forms platform for illustrating purposes (notice that the main concepts are common to unmanaged and managed code and it looks like things will remain the same for several years),&lt;/p&gt;  &lt;p&gt;On windows, GUIs apps rely on messages for signaling several kinds of operations. What this means is that mouse, keys events, etc end up generating a message that are send to the GUI thread’s message queue. The main job of this thread is to pump the messages that are queued on the message queue. &lt;/p&gt;  &lt;p&gt;In unmanaged code, pumping a message generally involves writing a loop that gets a message from the queue (GetMessage) and dispatches it (DispatchMessage) to a a special windows function (notice there’s always a windows function associated to a window – if you don’t create a custom one, you’ll end up with the default one). Windows functions will inspect the message and run some code in response to specific messages.&lt;/p&gt;  &lt;p&gt;Back to the managed world and windows forms, you’ll notice that all these details are hidden by several classes. For instance, pumping messages is supported through the &lt;a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.application.run.aspx"&gt;Application.Run&lt;/a&gt; call which you get by default on all the Windows Forms projects. Notice that this method “transforms” the thread on which it’s called into a GUI thread.&lt;/p&gt;  &lt;p&gt;Windows Forms also encapsulates the so called Windows function. In fact, if you look at the Control class, you’ll see that it exposes a protected &lt;a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.control.wndproc.aspx"&gt;WndProc&lt;/a&gt; method. Internally, this method translates the windows messages into events which you might (or not) handle from your app. Notice that even though there’s plenty of stuff exposed as events, you can still overload this method if you need to handle a windows message directly.&lt;/p&gt;  &lt;p&gt;As you can see, we can say that the final result of pumping a message is running some code that performs a specific action. In Windows Forms apps, this generally means handling an event. Now, after the previous paragraph, it should be obvious why you shouldn’t do much work from within your event handlers: if you do a lengthily operation from the GUI thread, you’re not letting it pump more messages, leading to a blocked window (something which we’ve all seen in the past - and probably cursed the guys that have written that app for it:)).&lt;/p&gt;  &lt;p&gt;Blocking the GUI thread isn’t such a good idea either. However, it’s important to recall that in windows you can block a thread while pumping messages from the message queue. The CLR does this automatically for you and you have no control over it (which is good and bad as we’ve seen in the past).&lt;/p&gt;  &lt;p&gt;Now, since you already know lot of things about multithreading, you know that you can easily execute that lengthily operation on a separated thread. The problem is that all windows controls have thread affinity and can only be updated from the GUI thread. This means that when we are on a secondary thread, we need to marshal the results back to the GUI thread if we need to change a property of a control.&lt;/p&gt;  &lt;p&gt;As you can see, using separate threads on GUI programming is a must for ensuring proper response from our application. However, it also needs special care for guaranteeing that everything works as expected. In the next posts we’ll start looking at some practical examples which show how to use multithreading on GUIs and on the internal details that support this kind of operations. Keep tuned!&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1696012" width="1" height="1"&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/_YAuQY5ZVb3CAFYaPmspMMRF644/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/_YAuQY5ZVb3CAFYaPmspMMRF644/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/_YAuQY5ZVb3CAFYaPmspMMRF644/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/_YAuQY5ZVb3CAFYaPmspMMRF644/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;</description><category domain="http://msmvps.com/blogs/luisabreu/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://msmvps.com/blogs/luisabreu/archive/tags/Multithreading/default.aspx">Multithreading</category><feedburner:origLink>http://msmvps.com/blogs/luisabreu/archive/2009/06/21/multithreading-why-multithreading-on-guis.aspx</feedburner:origLink></item><item><title>Multithreading: updating the code to support multiple asynchronous executions of one method</title><link>http://feedproxy.google.com/~r/Laneten/~3/2JISt4UtmdQ/multithreading-updating-the-code-to-support-multiple-asynchronous-executions-of-one-method.aspx</link><pubDate>Sat, 20 Jun 2009 14:26:42 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1695913</guid><dc:creator>luisabreu</dc:creator><slash:comments>0</slash:comments><wfw:commentRss>http://msmvps.com/blogs/luisabreu/rsscomments.aspx?PostID=1695913</wfw:commentRss><comments>http://msmvps.com/blogs/luisabreu/archive/2009/06/20/multithreading-updating-the-code-to-support-multiple-asynchronous-executions-of-one-method.aspx#comments</comments><description>&lt;p&gt;In the previous posts, we’ve seen how to implement the asynchronous event based pattern and how to support several features:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;&lt;a href="http://msmvps.com/blogs/luisabreu/archive/2009/06/17/multithreading-implementing-the-event-based-pattern.aspx"&gt;executing&lt;/a&gt; the task asynchronously; &lt;/li&gt;    &lt;li&gt;support &lt;a href="http://msmvps.com/blogs/luisabreu/archive/2009/06/20/multithreading-reporting-progress-on-the-asynchronous-task.aspx"&gt;progress&lt;/a&gt; notification; &lt;/li&gt;    &lt;li&gt;support &lt;a href="http://msmvps.com/blogs/luisabreu/archive/2009/06/18/multithreading-adding-cancel-to-the-initial-event-based-pattern-implementation.aspx"&gt;cancellation&lt;/a&gt;. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Today we’re going to update our &lt;a href="http://msmvps.com/blogs/luisabreu/archive/2009/06/20/multithreading-reporting-progress-on-the-asynchronous-task.aspx"&gt;initial code&lt;/a&gt; to support several simultaneous asynchronous calls of the same method. If you look at that &lt;a href="http://msmvps.com/blogs/luisabreu/archive/2009/06/20/multithreading-reporting-progress-on-the-asynchronous-task.aspx"&gt;code&lt;/a&gt;, you’ll notice that for supporting a single operation, we’re using several fields:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;an AsyncOperation (_currentOperation) instance that represents the current operation; &lt;/li&gt;    &lt;li&gt;a boolean field (_isRunning) which indicates if there’s currently a running operation; &lt;/li&gt;    &lt;li&gt;a boolean field used for supporting cancellation. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Going multi-method is not really complicated, though it means we need to pay more attention to the way the internal fields of the class are accessed. The first thing we’ll need is a container for storing several items. You probably recall from previous posts that we mentioned an optional Object parameter for several of the methods exposed by a class. This optional parameter stops being optional when we want to support several asynchronous operations. In practice, it’s used as a key that identifies a specific asynchronous execution. Notice that the consumer of the API must remember that key if it wants to get progress info or if it needs to cancel a running operation.&amp;#160; In this case, we’ll be using a Dictionary&amp;lt;Object, AsyncOperation&amp;gt; as the container that stores all the running asynchronous operations. &lt;/p&gt;  &lt;p&gt;Using a dictionary means that will have to translate the operations that relied on the fields into methods that use the dictionary. Here are the methods we’ve ended up adding to the &lt;a href="http://msmvps.com/blogs/luisabreu/archive/2009/06/20/multithreading-reporting-progress-on-the-asynchronous-task.aspx"&gt;previous&lt;/a&gt; class:&lt;/p&gt;  &lt;pre style="background-color:black;" class="code"&gt;&lt;span style="color:#ff8000;"&gt;private &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IDictionary&lt;/span&gt;&lt;span style="color:white;"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color:yellow;"&gt;Object&lt;/span&gt;&lt;span style="color:white;"&gt;, &lt;/span&gt;&lt;span style="color:yellow;"&gt;AsyncOperation&lt;/span&gt;&lt;span style="color:white;"&gt;&amp;gt; _operations = 
                  &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;new &lt;/span&gt;&lt;span style="color:yellow;"&gt;Dictionary&lt;/span&gt;&lt;span style="color:white;"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color:yellow;"&gt;Object&lt;/span&gt;&lt;span style="color:white;"&gt;, &lt;/span&gt;&lt;span style="color:yellow;"&gt;AsyncOperation&lt;/span&gt;&lt;span style="color:white;"&gt;&amp;gt;();
&lt;/span&gt;&lt;span style="color:#ff8000;"&gt;private void &lt;/span&gt;&lt;span style="color:white;"&gt;AddOperation(&lt;/span&gt;&lt;span style="color:yellow;"&gt;Object &lt;/span&gt;&lt;span style="color:white;"&gt;key, &lt;/span&gt;&lt;span style="color:yellow;"&gt;AsyncOperation &lt;/span&gt;&lt;span style="color:white;"&gt;operation) {
  &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;lock &lt;/span&gt;&lt;span style="color:white;"&gt;(_operations) {
    &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;if &lt;/span&gt;&lt;span style="color:white;"&gt;(_operations.ContainsKey(key)) {
      &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;throw new &lt;/span&gt;&lt;span style="color:yellow;"&gt;ArgumentException&lt;/span&gt;&lt;span style="color:white;"&gt;();
    }
    _operations.Add(key, operation);
  }
}
&lt;/span&gt;&lt;span style="color:#ff8000;"&gt;private &lt;/span&gt;&lt;span style="color:yellow;"&gt;AsyncOperation &lt;/span&gt;&lt;span style="color:white;"&gt;GetOperation(&lt;/span&gt;&lt;span style="color:yellow;"&gt;Object &lt;/span&gt;&lt;span style="color:white;"&gt;key) {
  &lt;/span&gt;&lt;span style="color:yellow;"&gt;AsyncOperation &lt;/span&gt;&lt;span style="color:white;"&gt;operation = &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;null&lt;/span&gt;&lt;span style="color:white;"&gt;;
  &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;lock &lt;/span&gt;&lt;span style="color:white;"&gt;(_operations) {
    operation = _operations[key];
  }
  &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;return &lt;/span&gt;&lt;span style="color:white;"&gt;operation;
}
&lt;/span&gt;&lt;span style="color:#ff8000;"&gt;private void &lt;/span&gt;&lt;span style="color:white;"&gt;CancelOperation(&lt;/span&gt;&lt;span style="color:yellow;"&gt;Object &lt;/span&gt;&lt;span style="color:white;"&gt;key) {
  &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;lock &lt;/span&gt;&lt;span style="color:white;"&gt;(_operations) {
    _operations[key] = &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;null&lt;/span&gt;&lt;span style="color:white;"&gt;;
  }
}
&lt;/span&gt;&lt;span style="color:#ff8000;"&gt;private void &lt;/span&gt;&lt;span style="color:white;"&gt;EndOperation(&lt;/span&gt;&lt;span style="color:yellow;"&gt;Object &lt;/span&gt;&lt;span style="color:white;"&gt;key) {
  &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;lock &lt;/span&gt;&lt;span style="color:white;"&gt;(_operations) {
    _operations.Remove(key);
  }
}
&lt;/span&gt;&lt;span style="color:#ff8000;"&gt;private &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Boolean &lt;/span&gt;&lt;span style="color:white;"&gt;IsRunning(&lt;/span&gt;&lt;span style="color:yellow;"&gt;Object &lt;/span&gt;&lt;span style="color:white;"&gt;key) {
  &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;var &lt;/span&gt;&lt;span style="color:white;"&gt;isRunning = &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;false&lt;/span&gt;&lt;span style="color:white;"&gt;;
  &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;lock &lt;/span&gt;&lt;span style="color:white;"&gt;(_operations) {
    isRunning = _operations.ContainsKey(key) &amp;amp;&amp;amp; 
                _operations[key] != &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;null&lt;/span&gt;&lt;span style="color:white;"&gt;;
  }
  &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;return &lt;/span&gt;&lt;span style="color:white;"&gt;isRunning;
}
&lt;/span&gt;&lt;span style="color:#ff8000;"&gt;private &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Boolean &lt;/span&gt;&lt;span style="color:white;"&gt;OperationWasCancelled(&lt;/span&gt;&lt;span style="color:yellow;"&gt;Object &lt;/span&gt;&lt;span style="color:white;"&gt;key) {
  &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Boolean &lt;/span&gt;&lt;span style="color:white;"&gt;cancelled = &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;false&lt;/span&gt;&lt;span style="color:white;"&gt;;
  &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;lock &lt;/span&gt;&lt;span style="color:white;"&gt;(_operations) {
    cancelled = _operations.ContainsKey(key) &amp;amp;&amp;amp; 
                _operations[key] == &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;null&lt;/span&gt;&lt;span style="color:white;"&gt;;
  }
  &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;return &lt;/span&gt;&lt;span style="color:white;"&gt;cancelled;
}&lt;/span&gt;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;As you can see, we’ve added several methods that lets cancel an operation (CancelOperation), check if an operation is running (IsRunning), check if an operation was cancelled (OperationWasCancelled) and clear an operation which has ended from the private dictionary (EndOperation). Notice that we’re using locks for ensuring proper dictionary access.&lt;/p&gt;

&lt;p&gt;There are a couple of interesting changes between the previous snippet and the old code: &lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;the first thing you should notice is that the asynchronous operations can only be identified by a key (we’ll see from where that key comes in the next paragraphs) and that’s why all the helper methods receive one. &lt;/li&gt;

  &lt;li&gt;if you compare the “running” concept implementation with the one we have in the previous snippet, you should notice that running means having a valid entry with the specified key (in the previous simpler code, we used a simple field for checking if a task was running); &lt;/li&gt;

  &lt;li&gt;cancelling means that we set the associated AsynchronousOperation to null but don’t remove the entry from the dictionary; &lt;/li&gt;

  &lt;li&gt;we’ve also got a helper method that should only be called when the asynchronous operation ends and is responsible for removing everything from the entry from the dictionary. &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The next thing we need to change is the IsPrimeAsync method. Besides adding the Object parameter used for identifying an asynchronous operation, we also need to change the internal code used by that method:&lt;/p&gt;

&lt;pre style="background-color:black;" class="code"&gt;&lt;span style="color:#ff8000;"&gt;public void &lt;/span&gt;&lt;span style="color:white;"&gt;IsPrimeAsync(&lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Int32 &lt;/span&gt;&lt;span style="color:white;"&gt;number, &lt;/span&gt;&lt;span style="color:yellow;"&gt;Object &lt;/span&gt;&lt;span style="color:white;"&gt;key) {
  &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;if &lt;/span&gt;&lt;span style="color:white;"&gt;(IsRunning(key)) {
      &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;throw new &lt;/span&gt;&lt;span style="color:yellow;"&gt;InvalidOperationException&lt;/span&gt;&lt;span style="color:white;"&gt;();
  }
  &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;var &lt;/span&gt;&lt;span style="color:white;"&gt;currentOperation = &lt;/span&gt;&lt;span style="color:yellow;"&gt;AsyncOperationManager&lt;/span&gt;&lt;span style="color:white;"&gt;.CreateOperation(&lt;/span&gt;&lt;span style="color:#ff8000;"&gt;null&lt;/span&gt;&lt;span style="color:white;"&gt;);
  AddOperation(key, currentOperation);
  &lt;/span&gt;&lt;span style="color:yellow;"&gt;ThreadPool&lt;/span&gt;&lt;span style="color:white;"&gt;.QueueUserWorkItem(state =&amp;gt;  {
    &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;var &lt;/span&gt;&lt;span style="color:white;"&gt;numberToCheck = (&lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Int32&lt;/span&gt;&lt;span style="color:white;"&gt;)number;
    &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;var &lt;/span&gt;&lt;span style="color:white;"&gt;isPrime = &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;false&lt;/span&gt;&lt;span style="color:white;"&gt;;
    &lt;/span&gt;&lt;span style="color:yellow;"&gt;Exception &lt;/span&gt;&lt;span style="color:white;"&gt;throwException = &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;null&lt;/span&gt;&lt;span style="color:white;"&gt;;
    &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;try &lt;/span&gt;&lt;span style="color:white;"&gt;{
      &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;if &lt;/span&gt;&lt;span style="color:white;"&gt;(number &amp;gt; 2) {
        isPrime = &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;true&lt;/span&gt;&lt;span style="color:white;"&gt;;
        &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;var &lt;/span&gt;&lt;span style="color:white;"&gt;half = number / 2;
        &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;var &lt;/span&gt;&lt;span style="color:white;"&gt;currentProgress = 0f;
        &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;for &lt;/span&gt;&lt;span style="color:white;"&gt;(&lt;/span&gt;&lt;span style="color:#ff8000;"&gt;var &lt;/span&gt;&lt;span style="color:white;"&gt;i = 2; i &amp;lt; half &amp;amp;&amp;amp; 
                  !OperationWasCancelled(key); i++) {
            &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;if &lt;/span&gt;&lt;span style="color:white;"&gt;(number % i == 0) {
                isPrime = &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;false&lt;/span&gt;&lt;span style="color:white;"&gt;;
                &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;break&lt;/span&gt;&lt;span style="color:white;"&gt;;
            }
            currentProgress = ((&lt;/span&gt;&lt;span style="color:#ff8000;"&gt;float&lt;/span&gt;&lt;span style="color:white;"&gt;)i  / (&lt;/span&gt;&lt;span style="color:#ff8000;"&gt;float&lt;/span&gt;&lt;span style="color:white;"&gt;)half) * 100;
            currentOperation.Post(
              evtState =&amp;gt; OnProgressChanged(
                  (&lt;/span&gt;&lt;span style="color:yellow;"&gt;ProgressChangedEventArgs&lt;/span&gt;&lt;span style="color:white;"&gt;)evtState),
                  &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;new &lt;/span&gt;&lt;span style="color:yellow;"&gt;ProgressChangedEventArgs&lt;/span&gt;&lt;span style="color:white;"&gt;(
                    (&lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Int32&lt;/span&gt;&lt;span style="color:white;"&gt;)currentProgress, key));
          }                                
      }
    } 
    &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;catch &lt;/span&gt;&lt;span style="color:white;"&gt;(&lt;/span&gt;&lt;span style="color:yellow;"&gt;Exception &lt;/span&gt;&lt;span style="color:white;"&gt;ex) {
        throwException = ex;
    } 
    &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;finally &lt;/span&gt;&lt;span style="color:white;"&gt;{
        NotifyEndOfOperation(
          numberToCheck, 
          isPrime, 
          OperationWasCancelled(key), 
          throwException, 
          key, 
          currentOperation);
    }
  }, number);
}&lt;/span&gt;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;I think there’s not much to say about this method: the principles are the same as before but now everything is encapsulated by several helper methods. As you can see, we’ve updated the code use for propagating progress (now we pass the key that identifies the operation, instead of passing null) and we’ve also changed the API of the NotifyEndOfOperation so that it also receives the associated AsyncOperation instance and its key (we could always get the key from the UserSuppliedState property of the AsyncOperation instance, but I preferred to be explicit about it). Here’s the code for that method:&lt;/p&gt;

&lt;pre style="background-color:black;" class="code"&gt;&lt;span style="color:#ff8000;"&gt;private void &lt;/span&gt;&lt;span style="color:white;"&gt;NotifyEndOfOperation( &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Int32 &lt;/span&gt;&lt;span style="color:white;"&gt;numberToTest,
  &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Boolean &lt;/span&gt;&lt;span style="color:white;"&gt;isPrime,
  &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Boolean &lt;/span&gt;&lt;span style="color:white;"&gt;cancelled, 
  &lt;/span&gt;&lt;span style="color:yellow;"&gt;Exception &lt;/span&gt;&lt;span style="color:white;"&gt;thrownException,
  &lt;/span&gt;&lt;span style="color:yellow;"&gt;Object &lt;/span&gt;&lt;span style="color:white;"&gt;key,
  &lt;/span&gt;&lt;span style="color:yellow;"&gt;AsyncOperation &lt;/span&gt;&lt;span style="color:white;"&gt;currentOperation ){
    &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;var &lt;/span&gt;&lt;span style="color:white;"&gt;evt = &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;new &lt;/span&gt;&lt;span style="color:yellow;"&gt;PrimeNumberVerificationCompletedEventArgs&lt;/span&gt;&lt;span style="color:white;"&gt;(
            numberToTest, isPrime, thrownException, cancelled, key);
    currentOperation.PostOperationCompleted(
          evtState =&amp;gt; {
            EndOperation(key);
            OnPrimeNumberCompleted(
              (&lt;/span&gt;&lt;span style="color:yellow;"&gt;PrimeNumberVerificationCompletedEventArgs&lt;/span&gt;&lt;span style="color:white;"&gt;)evtState);
         }, 
        evt);
}&lt;/span&gt;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;The main point of interest here is that we’ve updated the instantiation of the PrimeNumberVerificationCompletedEventArgs so that if is able to flow the key that identifies the operation that ended. Notice also that we clear the current AsyncOperation from the dictionary before notifying the user of the completion of the task.&lt;/p&gt;

&lt;p&gt;The only thing needed is updating the code used for cancelling a running task: &lt;/p&gt;

&lt;pre style="background-color:black;" class="code"&gt;&lt;span style="color:#ff8000;"&gt;public void &lt;/span&gt;&lt;span style="color:white;"&gt;CancelAsync(&lt;/span&gt;&lt;span style="color:yellow;"&gt;Object &lt;/span&gt;&lt;span style="color:white;"&gt;key) {
  &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;if &lt;/span&gt;&lt;span style="color:white;"&gt;(OperationWasCancelled(key)) {
      &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;return&lt;/span&gt;&lt;span style="color:white;"&gt;;
  }
  CancelOperation(key);
}&lt;/span&gt;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;And that’s it. With this post, I’d say that there really isn’t much more to say about this pattern. Keep tuned for more on multithreading apps!&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1695913" width="1" height="1"&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/hSxzYUIhX7X07SWP8JLNaSq9YDg/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/hSxzYUIhX7X07SWP8JLNaSq9YDg/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/hSxzYUIhX7X07SWP8JLNaSq9YDg/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/hSxzYUIhX7X07SWP8JLNaSq9YDg/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;</description><category domain="http://msmvps.com/blogs/luisabreu/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://msmvps.com/blogs/luisabreu/archive/tags/Multithreading/default.aspx">Multithreading</category><feedburner:origLink>http://msmvps.com/blogs/luisabreu/archive/2009/06/20/multithreading-updating-the-code-to-support-multiple-asynchronous-executions-of-one-method.aspx</feedburner:origLink></item><item><title>Multithreading: reporting progress on the asynchronous task</title><link>http://feedproxy.google.com/~r/Laneten/~3/7-Z0-YxOESw/multithreading-reporting-progress-on-the-asynchronous-task.aspx</link><pubDate>Sat, 20 Jun 2009 12:06:54 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1695905</guid><dc:creator>luisabreu</dc:creator><slash:comments>0</slash:comments><wfw:commentRss>http://msmvps.com/blogs/luisabreu/rsscomments.aspx?PostID=1695905</wfw:commentRss><comments>http://msmvps.com/blogs/luisabreu/archive/2009/06/20/multithreading-reporting-progress-on-the-asynchronous-task.aspx#comments</comments><description>&lt;p&gt;I know that I’ve &lt;a href="http://msmvps.com/blogs/luisabreu/archive/2009/06/18/multithreading-adding-cancel-to-the-initial-event-based-pattern-implementation.aspx"&gt;said&lt;/a&gt; that the next post of the &lt;a href="http://msmvps.com/blogs/luisabreu/archive/tags/Multithreading/default.aspx"&gt;series&lt;/a&gt; would be on how to support several asynchronous tasks. However, I was reminded by a friend that I didn’t had any post on how to support the optional progress info feature. So, I decided to take a small detour today and we’ll see how we can modify our class so that it is able to report progress back to the user.&lt;/p&gt;  &lt;p&gt;As we’ve seen, progress is exposed through an event named ProgressChanged, of type ProgressChangedEventHandler (notice that if you have several diferent asynchronous method, then you should name the event XXXProgressChanged, where XXX is the name of the asynchronous method).&lt;/p&gt;  &lt;p&gt;Here’s the code we’re using to fire the event:&lt;/p&gt;  &lt;p style="background-color:black;"&gt;&lt;span style="color:#ff8000;"&gt;public event &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ProgressChangedEventHandler &lt;/span&gt;&lt;span style="color:white;"&gt;ProgressChanged;      &lt;br /&gt;&lt;/span&gt;&lt;span style="color:#ff8000;"&gt;protected void &lt;/span&gt;&lt;span style="color:white;"&gt;OnProgressChanged(&lt;/span&gt;&lt;span style="color:yellow;"&gt;ProgressChangedEventArgs &lt;/span&gt;&lt;span style="color:white;"&gt;evt){      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;if &lt;/span&gt;&lt;span style="color:white;"&gt;(ProgressChanged != &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;null&lt;/span&gt;&lt;span style="color:white;"&gt;) {      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; ProgressChanged(&lt;/span&gt;&lt;span style="color:#ff8000;"&gt;this&lt;/span&gt;&lt;span style="color:white;"&gt;, evt);      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }       &lt;br /&gt;}&lt;/span&gt;&lt;/p&gt;  &lt;p&gt;As you can see, this is standard stuff, ie, we’ve added the event and then an OnEventName method which is responsible for firing the event (btw, keep in mind that if the class you’re building isn’t sealed, then you should make the method virtual so that a derived class can use overrides as a way to “handle” the event ).&lt;/p&gt;  &lt;p&gt;As you might guess by now, progress report must come from the method that does the work. In this case, we’re talking about an anonymous method that is passed to the ThreadPool.QueueUserWorkItem method. In this example, calculating the progress is easy and depends on the total number of elements used in the for loop:&lt;/p&gt;  &lt;pre style="background-color:black;" class="code"&gt;&lt;span style="color:#ff8000;"&gt;public void &lt;/span&gt;&lt;span style="color:white;"&gt;IsPrimeAsync(&lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Int32 &lt;/span&gt;&lt;span style="color:white;"&gt;number) {
  &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;if &lt;/span&gt;&lt;span style="color:white;"&gt;(_isRunning) {
      &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;throw new &lt;/span&gt;&lt;span style="color:yellow;"&gt;InvalidOperationException&lt;/span&gt;&lt;span style="color:white;"&gt;();
  }
  _isRunning = &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;true&lt;/span&gt;&lt;span style="color:white;"&gt;;
  _currentOperation = &lt;/span&gt;&lt;span style="color:yellow;"&gt;AsyncOperationManager&lt;/span&gt;&lt;span style="color:white;"&gt;.CreateOperation(&lt;/span&gt;&lt;span style="color:#ff8000;"&gt;null&lt;/span&gt;&lt;span style="color:white;"&gt;);
  &lt;/span&gt;&lt;span style="color:yellow;"&gt;ThreadPool&lt;/span&gt;&lt;span style="color:white;"&gt;.QueueUserWorkItem(state =&amp;gt;  {
      &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;var &lt;/span&gt;&lt;span style="color:white;"&gt;numberToCheck = (&lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Int32&lt;/span&gt;&lt;span style="color:white;"&gt;)number;
      &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;var &lt;/span&gt;&lt;span style="color:white;"&gt;isPrime = &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;false&lt;/span&gt;&lt;span style="color:white;"&gt;;
      &lt;/span&gt;&lt;span style="color:yellow;"&gt;Exception &lt;/span&gt;&lt;span style="color:white;"&gt;throwException = &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;null&lt;/span&gt;&lt;span style="color:white;"&gt;;
      &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;try &lt;/span&gt;&lt;span style="color:white;"&gt;{
        &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;if &lt;/span&gt;&lt;span style="color:white;"&gt;(number &amp;gt; 2) {
          isPrime = &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;true&lt;/span&gt;&lt;span style="color:white;"&gt;;
          &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;var &lt;/span&gt;&lt;span style="color:white;"&gt;half = number / 2;
          &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;var &lt;/span&gt;&lt;span style="color:white;"&gt;currentProgress = 0f;
          &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;for &lt;/span&gt;&lt;span style="color:white;"&gt;(&lt;/span&gt;&lt;span style="color:#ff8000;"&gt;var &lt;/span&gt;&lt;span style="color:white;"&gt;i = 2; i &amp;lt; half &amp;amp;&amp;amp; !_cancelOperation; i++) {
              &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;if &lt;/span&gt;&lt;span style="color:white;"&gt;(number % i == 0) {
                  isPrime = &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;false&lt;/span&gt;&lt;span style="color:white;"&gt;;
                  &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;break&lt;/span&gt;&lt;span style="color:white;"&gt;;
              }
              currentProgress = ((&lt;/span&gt;&lt;span style="color:#ff8000;"&gt;float&lt;/span&gt;&lt;span style="color:white;"&gt;)i  / (&lt;/span&gt;&lt;span style="color:#ff8000;"&gt;float&lt;/span&gt;&lt;span style="color:white;"&gt;)half) * 100;
              _currentOperation.Post(
                      evtState =&amp;gt; OnProgressChanged(
                             (&lt;/span&gt;&lt;span style="color:yellow;"&gt;ProgressChangedEventArgs&lt;/span&gt;&lt;span style="color:white;"&gt;)evtState ),
                      &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;new &lt;/span&gt;&lt;span style="color:yellow;"&gt;ProgressChangedEventArgs&lt;/span&gt;&lt;span style="color:white;"&gt;(&lt;br /&gt;                           (&lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Int32&lt;/span&gt;&lt;span style="color:white;"&gt;)currentProgress, &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;null&lt;/span&gt;&lt;span style="color:white;"&gt;));
            }                                
        }
      } 
      &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;catch &lt;/span&gt;&lt;span style="color:white;"&gt;(&lt;/span&gt;&lt;span style="color:yellow;"&gt;Exception &lt;/span&gt;&lt;span style="color:white;"&gt;ex) {
          throwException = ex;
      } 
      &lt;/span&gt;&lt;span style="color:#ff8000;"&gt;finally &lt;/span&gt;&lt;span style="color:white;"&gt;{
          NotifyEndOfOperation(numberToCheck, &lt;br /&gt;              isPrime, _cancelOperation, throwException);
      }

    }, number);
}&lt;/span&gt;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;If you compare this code with the previous snippet, you’ll see that we added a currentProgress local variable for tracking the progress of the current operation and that we’re using our AsyncOperation instance (_currentOperation field) for marshalling the results and invoking the OnProgressChanged event from the “main thread” (where “main thread” is the thread that started the operation). And that’s it. From this point on, you can also get progress information by hooking up the ProgressChanged event:&lt;/p&gt;

&lt;pre style="background-color:black;" class="code"&gt;&lt;span style="color:white;"&gt;work.ProgressChanged += (sender, e) =&amp;gt; &lt;/span&gt;&lt;span style="color:yellow;"&gt;{ //do something here with progress info}&lt;/span&gt;&lt;span style="color:white;"&gt;;&lt;/span&gt;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;And that’s it for today. On the next post, we’ll talk about the changes we need to make to the current code so that we can support several asynchronous executions of the IsPrimeAsync method. Keep tuned!&lt;/p&gt;

&lt;p&gt;PS: I’ve followed &lt;a href="http://devlicio.us/blogs/tuna_toksoz"&gt;Tuna&lt;/a&gt;’s twitter suggestion and I’ve used a plug-in for showing code in color. Do you guys prefer it this way?&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1695905" width="1" height="1"&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/bCdLrSmxPhtn-_qnArxEYVv3PW8/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/bCdLrSmxPhtn-_qnArxEYVv3PW8/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/bCdLrSmxPhtn-_qnArxEYVv3PW8/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/bCdLrSmxPhtn-_qnArxEYVv3PW8/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;</description><category domain="http://msmvps.com/blogs/luisabreu/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://msmvps.com/blogs/luisabreu/archive/tags/Multithreading/default.aspx">Multithreading</category><feedburner:origLink>http://msmvps.com/blogs/luisabreu/archive/2009/06/20/multithreading-reporting-progress-on-the-asynchronous-task.aspx</feedburner:origLink></item><item><title>Multithreading: adding cancelation to the initial event based pattern implementation</title><link>http://feedproxy.google.com/~r/Laneten/~3/GvLgqsvJeXc/multithreading-adding-cancel-to-the-initial-event-based-pattern-implementation.aspx</link><pubDate>Thu, 18 Jun 2009 21:45:36 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1695813</guid><dc:creator>luisabreu</dc:creator><slash:comments>3</slash:comments><wfw:commentRss>http://msmvps.com/blogs/luisabreu/rsscomments.aspx?PostID=1695813</wfw:commentRss><comments>http://msmvps.com/blogs/luisabreu/archive/2009/06/18/multithreading-adding-cancel-to-the-initial-event-based-pattern-implementation.aspx#comments</comments><description>&lt;p&gt;Today we’re going to improve the &lt;a href="http://msmvps.com/blogs/luisabreu/archive/2009/06/17/multithreading-implementing-the-event-based-pattern.aspx"&gt;code&lt;/a&gt; we’ve started writing yesterday: we’re adding canceling support. As you might recall, in our last post we’ve built a simple class which supports a single asynchronous operation at a time. Since we only support one asynchronous operation at a time and we can only start one asynchronous operation from our class, then we only need to add a parameterless CancelAsync method. &lt;/p&gt;  &lt;p&gt;Here’s how you might implement the CancelAsync method:&lt;/p&gt;  &lt;p&gt;public void CancelAsync() {   &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; if (!_isRunning) {    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; return;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; _cancelOperation = true;    &lt;br /&gt;}&lt;/p&gt;  &lt;p&gt;As you can see, we need to add a _cancel operation field which is used for notifying the helper method that runs in asynchronous mode that it should stop. This means that we need to change our asynchronous method slightly so that it checks that value in the for cycle and passes that value for the PrimeNumberVerificationCompletedEventArgs instance passed to whoever consumes the PrimeNumberCompleted event. Since I’ve cheated a little bit in the previous post, we’ve already got the hooking points for flowing the needed information. This means that changes are mostly concentrated on the IsPrimeAsync method:&lt;/p&gt;  &lt;p&gt;public void IsPrimeAsync(Int32 number) {   &lt;br /&gt;&amp;#160; if (_isRunning) {    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; throw new InvalidOperationException();    &lt;br /&gt;&amp;#160; }    &lt;br /&gt;&amp;#160; _isRunning = true;    &lt;br /&gt;&amp;#160; _currentOperation = AsyncOperationManager.CreateOperation(null);    &lt;br /&gt;&amp;#160; ThreadPool.QueueUserWorkItem(state =&amp;gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; {    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; var numberToCheck = (Int32)number;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; var isPrime = false;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Exception throwException = null;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; try {    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; if (number &amp;gt; 2) {    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; isPrime = true;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; var half = number / 2;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; for (var i = 2; i &amp;lt; half &amp;amp;&amp;amp; &lt;strong&gt;!_cancelOperation&lt;/strong&gt;; i++) {    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; if (number % i == 0) {    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; isPrime = false;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; break;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; catch (Exception ex) {    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; throwException = ex;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; finally {    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; NotifyEndOfOperation(numberToCheck,     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; isPrime,     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; _&lt;strong&gt;cancelOperation&lt;/strong&gt;,     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; throwException);    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; } &lt;/p&gt;  &lt;p&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }, number);   &lt;br /&gt;}&lt;/p&gt;  &lt;p&gt;There’s still one thing missing: we need to clean up the _cancelOperation flag when that asynchronous operation ends. This can be done from within the anonymous method we’re using inside the NotifyEndOfOperation method:&lt;/p&gt;  &lt;p&gt;private void NotifyEndOfOperation( Int32 numberToTest,   &lt;br /&gt;&amp;#160; Boolean isPrime,    &lt;br /&gt;&amp;#160; Boolean cancelled,     &lt;br /&gt;&amp;#160; Exception thrownException ){    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; var evt = new PrimeNumberVerificationCompletedEventArgs(    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; numberToTest,     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; isPrime,     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; thrownException,     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; cancelled,     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; null);    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; _currentOperation.PostOperationCompleted(    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; state =&amp;gt; {    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; _isRunning = false;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;strong&gt;_cancelOperation = false;     &lt;br /&gt;&lt;/strong&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; OnPrimeNumberCompleted((PrimeNumberVerificationCompletedEventArgs)state);    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; },     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; evt);    &lt;br /&gt;}&lt;/p&gt;  &lt;p&gt;And that’s it. As you can see, supporting cancelation is not really that hard. We’ll keep improving this sample and on the next post we’ll see how we can improve our code so that it supports multiple asynchronous operations. Keep tuned.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1695813" width="1" height="1"&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/bL5gDKxByo_TSZ-HpW4I_iPq8i8/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/bL5gDKxByo_TSZ-HpW4I_iPq8i8/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/bL5gDKxByo_TSZ-HpW4I_iPq8i8/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/bL5gDKxByo_TSZ-HpW4I_iPq8i8/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;</description><category domain="http://msmvps.com/blogs/luisabreu/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://msmvps.com/blogs/luisabreu/archive/tags/Multithreading/default.aspx">Multithreading</category><feedburner:origLink>http://msmvps.com/blogs/luisabreu/archive/2009/06/18/multithreading-adding-cancel-to-the-initial-event-based-pattern-implementation.aspx</feedburner:origLink></item></channel></rss>
