<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Ticklish Techs &#187; dotnet</title>
	<atom:link href="http://www.ticklishtechs.net/tag/dotnet/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.ticklishtechs.net</link>
	<description>a mostly .NET but also some other cool techs blog</description>
	<lastBuildDate>Wed, 05 Jan 2011 21:44:29 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.4</generator>
		<item>
		<title>Developing R#-PlugIns with a little comfort?</title>
		<link>http://www.ticklishtechs.net/2011/01/03/developing-r-plugins-with-a-little-comfort/</link>
		<comments>http://www.ticklishtechs.net/2011/01/03/developing-r-plugins-with-a-little-comfort/#comments</comments>
		<pubDate>Mon, 03 Jan 2011 12:44:16 +0000</pubDate>
		<dc:creator>Wolfram Bernhardt</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[coding]]></category>
		<category><![CDATA[dotnet]]></category>
		<category><![CDATA[resharper]]></category>
		<category><![CDATA[visual studio]]></category>
		<category><![CDATA[visual studio 2010]]></category>

		<guid isPermaLink="false">http://www.ticklishtechs.net/?p=342</guid>
		<description><![CDATA[I am playing around with R#-plugins these days. I have started off with this nice introduction. Unfortunately it silences about some problems that may occur to you in the beginning. 1) When trying to copy the given source code you&#8217;ll mention that all the classes are unknown to Visual Studio, because all a lot of [...]]]></description>
			<content:encoded><![CDATA[<p>I am playing around with R#-plugins these days. I have started off with <a href="http://devlicio.us/blogs/hadi_hariri/archive/2010/01/12/writing-plug-ins-for-resharper-part-1-of-undefined.aspx">this</a> nice introduction. Unfortunately it silences about some problems that may occur to you in the beginning.</p>
<p>1) When trying to copy the given source code you&#8217;ll mention that all the classes are unknown to Visual Studio, because all a lot of references are missing. So far I have no clue about the R#-class-architecture. So I started <a href="http://www.red-gate.com/products/dotnet-development/reflector/">.NET Reflector</a>, open ALL the .dlls in the R#/bin-folder into Reflector and use the search to find the .dlls to reference in my project.</p>
<p>2) When you have your first R#-plugin ready you want to test it. To do so you have to copy the dll containing your plugin in the R#-plugin folder. You may want to do this in a post-build event like this:</p>
<p><code><br />
copy $(TargetPath) "C:\Program Files (x86)\JetBrains\ReSharper\v5.1\Bin\PlugIns\WobTest"<br />
</code></p>
<p>When you build your project with this post-build event it fails. This doesn&#8217;t work for two reasons. First: Win 7 denies access to that folder. Second: after another start of Visual Studio R# has loaded the plugin so you can&#8217;t copy a newer version over it.</p>
<p>My solution to this is a .cmd that starts Visual Studio without R# (<code>devenv /safemode</code>). I run this .cmd as administrator. </p>
<p>Now at least I can debug my plugins by starting another instance of Visual Studio (not in safemode!)</p>
<p>This solution is not cool, because developing R#-plugin without using R# in the development-process sucks&#8230;. any ideas?</p>
<h3>a better solution&#8230;</h3>
<p>Some minutes after I published this post, Benjamin pointed me to <a href="http://www.codeproject.com/KB/cs/r_gettingStarted.aspx">this</a> page. Forget about my lines to 2). You don&#8217;t need a silly .cmd run as administrator not a post-build event. All you need to do is to start your debugging Visual Studio the the command line option /ReSharper.Plugin followed by the path to your plugin-dll.<br />
<code><br />
/ReSharper.Plugin "R:\sandbox\ReSharperPlugInTest\PublicGoesVirtual\PublicGoesVirtual\bin\Debug\PublicGoesVirtual.dll"</code></p>
]]></content:encoded>
			<wfw:commentRss>http://www.ticklishtechs.net/2011/01/03/developing-r-plugins-with-a-little-comfort/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Be careful with certain ctors of XmlSerializer</title>
		<link>http://www.ticklishtechs.net/2010/07/23/be-careful-with-certain-ctors-of-xmlserializer/</link>
		<comments>http://www.ticklishtechs.net/2010/07/23/be-careful-with-certain-ctors-of-xmlserializer/#comments</comments>
		<pubDate>Fri, 23 Jul 2010 06:07:49 +0000</pubDate>
		<dc:creator>Benjamin Schröter</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[coding]]></category>
		<category><![CDATA[dotnet]]></category>
		<category><![CDATA[performance]]></category>

		<guid isPermaLink="false">http://www.ticklishtechs.net/2010/07/23/be-careful-with-certain-ctors-of-xmlserializer/</guid>
		<description><![CDATA[In my current project we’re using XmlSerializer a lot. At some point I need to write about 400 files with the XmlSerializer. For some reason I created a new XmlSerializer for each of these files. I discovered during debugging a lot of debug messages in Visual Studio output window like: 'Application.vshost.exe' (Managed (v4.0.30319)): Loaded 'm0dayvr5' [...]]]></description>
			<content:encoded><![CDATA[<p>In my current project we’re using <a href="http://msdn.microsoft.com/en-us/library/swxzdhc0.aspx">XmlSerializer</a> a lot. At some point I need to write about 400 files with the XmlSerializer. For some reason I created a new XmlSerializer for each of these files.</p>
<p>I discovered during debugging a lot of debug messages in Visual Studio output window like:</p>
<table border="1">
<tbody>
<tr>
<td>
<pre>'Application.vshost.exe' (Managed (v4.0.30319)): Loaded 'm0dayvr5'
'Application.vshost.exe' (Managed (v4.0.30319)): Loaded 'oxxqw1rq'
'Application.vshost.exe' (Managed (v4.0.30319)): Loaded 'dgh3mgtl'
'Application.vshost.exe' (Managed (v4.0.30319)): Loaded '00sdpqlv'
'Application.vshost.exe' (Managed (v4.0.30319)): Loaded 'yokpozj4'</pre>
</td>
</tr>
</tbody>
</table>
<p>&#160;</p>
<p>Then I remembered that the XmlSerializer creates dynamic assemblies during runtime and loaded them into the AppDomain (and never unloads these assemblies since you cannot unload from an AppDoamin). In the <a href="http://msdn.microsoft.com/en-us/library/swxzdhc0.aspx">MSDN article</a> I found a solution that explains this behavior:</p>
<blockquote>
<h5>Dynamically Generated Assemblies</h5>
<p>To increase performance, the XML serialization infrastructure dynamically generates assemblies to serialize and deserialize specified types. The infrastructure finds and reuses those assemblies. This behavior occurs only when using the following constructors:</p>
<p><a href="http://msdn.microsoft.com/en-us/library/71s92ee1.aspx">XmlSerializer.XmlSerializer(Type)</a></p>
<p><a href="http://msdn.microsoft.com/en-us/library/kw0f5wee.aspx">XmlSerializer.XmlSerializer(Type, String)</a></p>
<p><strong><em>If you use any of the other constructors, multiple versions of the same assembly are generated and never unloaded, which results in a memory leak and poor performance.</em></strong> The easiest solution is to use one of the previously mentioned two constructors. Otherwise, you must cache the assemblies in a Hashtable, as shown in the following example.</p>
</blockquote>
<p>Of course you can use any other data structure to do the caching. But you have to do it on your own if you do not use the two mentioned constructors. I’ve got no idea why Microsoft builds caching into the code for some constructors and not for others, but that’s the way it is.</p>
<h3>Some performance measurements</h3>
<p>I didn’t build a great benchmark, but at least I got a few numbers. Serializing multiple files without caching takes on my machine about 140ms in debug mode and 130ms in release mode. Each time. With caching only the first file takes this 140 / 130ms and every additional file took about 8ms (debug) or 6ms (release).</p>
<p>That’s a speedup of about 17x to 20x!</p>
<p>And you do not produce memory leaks!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.ticklishtechs.net/2010/07/23/be-careful-with-certain-ctors-of-xmlserializer/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Creating a Setup with Visual Studio 2010 for an application that needs the full .net 4.0 framework</title>
		<link>http://www.ticklishtechs.net/2010/06/09/creating-a-setup-with-visual-studio-2010-for-an-application-that-needs-the-full-net-4-0-framework/</link>
		<comments>http://www.ticklishtechs.net/2010/06/09/creating-a-setup-with-visual-studio-2010-for-an-application-that-needs-the-full-net-4-0-framework/#comments</comments>
		<pubDate>Wed, 09 Jun 2010 12:50:48 +0000</pubDate>
		<dc:creator>Benjamin Schröter</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[dotnet]]></category>
		<category><![CDATA[dotnet3.5]]></category>
		<category><![CDATA[dotnet4.0]]></category>
		<category><![CDATA[msi]]></category>
		<category><![CDATA[setup]]></category>
		<category><![CDATA[visual studio]]></category>

		<guid isPermaLink="false">http://www.ticklishtechs.net/2010/06/09/creating-a-setup-with-visual-studio-2010-for-an-application-that-needs-the-full-net-4-0-framework/</guid>
		<description><![CDATA[When using Visual Studio 2010 or any other version to create msi setups you can define prerequisites that need to be installed before the application will install. For most .NET applications this will be at least the .NET Framework itself. But from version 3.5 on there are two editions of this framework: the Client Profile [...]]]></description>
			<content:encoded><![CDATA[<p>When using Visual Studio 2010 or any other version to create msi setups you can define prerequisites that need to be installed before the application will install. For most .NET applications this will be at least the .NET Framework itself. But from version 3.5 on there are two editions of this framework: the Client Profile and the Full Framework.</p>
<p>I created a setup and changed the prerequisites from Client Profile to the Full Framework. When testing this on a virgin machine the setup told me that I need to install the .NET 4.0 framework (that’s right) but then it directs me to the download of the Client Profile only.</p>
<p>To fix this, you have to change the InstallUrl of the .NET Framework Launch Condition:</p>
<ul>
<li>right-click on the setup project in solution explorer and choose View –&gt; Launch Conditions</li>
<li>here you will find a Launch Condition for the .NET Framework</li>
<li>select this Launch Condition and open the Properties Window</li>
<li>there you will find the InstallUrl property</li>
</ul>
<p>For the full .net 4.0 Framework change this URL to <a title="http://go.microsoft.com/fwlink/?LinkId=186913" href="http://go.microsoft.com/fwlink/?LinkId=186913">http://go.microsoft.com/fwlink/?LinkId=186913</a></p>
<p>For the Client Profile of the .net 4.0 Framework the URL can stay as it is: <a title="http://go.microsoft.com/fwlink/?LinkId=131000" href="http://go.microsoft.com/fwlink/?LinkId=131000">http://go.microsoft.com/fwlink/?LinkId=131000</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.ticklishtechs.net/2010/06/09/creating-a-setup-with-visual-studio-2010-for-an-application-that-needs-the-full-net-4-0-framework/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Be careful when using GetCallingAssembly() and always use the release build for testing</title>
		<link>http://www.ticklishtechs.net/2010/03/04/be-careful-when-using-getcallingassembly-and-always-use-the-release-build-for-testing/</link>
		<comments>http://www.ticklishtechs.net/2010/03/04/be-careful-when-using-getcallingassembly-and-always-use-the-release-build-for-testing/#comments</comments>
		<pubDate>Thu, 04 Mar 2010 17:46:24 +0000</pubDate>
		<dc:creator>Benjamin Schröter</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[coding]]></category>
		<category><![CDATA[debugging]]></category>
		<category><![CDATA[dotnet]]></category>
		<category><![CDATA[dotnet3.5]]></category>

		<guid isPermaLink="false">http://www.ticklishtechs.net/2010/03/04/be-careful-when-using-getcallingassembly-and-always-use-the-release-build-for-testing/</guid>
		<description><![CDATA[This looks like such a innocent method but it lead to big trouble in one of my projects. But lets start with when someone would use this method that is declared as a static method in the Assembly class. In the MSDN you can read: Returns the Assembly of the method that invoked the currently [...]]]></description>
			<content:encoded><![CDATA[<p>This looks like such a innocent method but it lead to big trouble in one of my projects. But lets start with when someone would use this method that is declared as a static method in the <code>Assembly</code> class. In the MSDN you can <a href="http://msdn.microsoft.com/en-us/library/system.reflection.assembly.getcallingassembly.aspx">read</a>:</p>
<blockquote><p>Returns the Assembly of the method that invoked the currently executing method.</p></blockquote>
<p>In our project we had an assembly with a lot of helper methods. On of these gets resources from the calling assembly. In various places of our code we called this method to get icons or other resources. This method used exactly this <code>GetCallingAssembly()</code> method to figure out what assembly to look for resources.</p>
<p>That worked pretty good in debug mode but exceptions were thrown in release mode. We could not understand what is going on. It became even worse: when we build a release version and tried to debug that version (using Visual Studio Debugger) in worked again. It looked like a <a href="http://en.wikipedia.org/wiki/Heisenbug#Heisenbug">heisenbug</a>.</p>
<p>It took us some time to figure out what is also written in <a href="http://msdn.microsoft.com/en-us/library/system.reflection.assembly.getcallingassembly%28VS.85%29.aspx">MSDN</a>:</p>
<blockquote><p>If the method that calls the <code>GetCallingAssembly</code> method is expanded inline by the compiler (that is, if the compiler inserts the function body into the emitted Microsoft intermediate language (MSIL), rather than emitting a function call), then the assembly returned by the <code>GetCallingAssembly</code> method is the assembly containing the inline code. This might be different from the assembly that contains the original method. To ensure that a method that calls the <code>GetCallingAssembly</code> method is not inlined by the compiler, you can apply the <code>MethodImplAttribute</code> attribute with <code>MethodImplOptions.NoInlining</code>.</p></blockquote>
<p>The JIT compiler moves code around to optimize for performance. Small methods (up to about 56 Byte IL-Code if I remember it right) can be inlined where the method call was before. But the compiler does this only in release, not in debug mode. Also when attaching the debugger to our release build the JIT compiler stopped inlining to enable debugging and our bug was gone.</p>
<p>After understanding this, the fix is easy. Just don’t allow the compiler to inline that particular method that calls <code>Assembly.GetCallingAssembly()</code>. Then the method stays in the assembly where the source code is written and everything will be fine.</p>
<pre class="code">[<span style="color: #2b91af;">MethodImplAttribute</span>(<span style="color: #2b91af;">MethodImplOptions</span>.NoInlining)]
<span style="color: blue;">public void </span>SomeFunction(<span style="color: blue;">int </span>i)
{
    <span style="color: green;">// ...
    </span><span style="color: blue;">var </span>a = <span style="color: #2b91af;">Assembly</span>.GetCallingAssembly();
    <span style="color: green;">// ...
</span>}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>This attribute does the trick and I recommend to use it on all methods that call <code>GetCallingAssembly()</code> and can be called form another assembly and need the <em>real </em>calling assembly.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.ticklishtechs.net/2010/03/04/be-careful-when-using-getcallingassembly-and-always-use-the-release-build-for-testing/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>A Change event for Dependency Properties</title>
		<link>http://www.ticklishtechs.net/2010/02/15/a-change-event-for-dependency-properties/</link>
		<comments>http://www.ticklishtechs.net/2010/02/15/a-change-event-for-dependency-properties/#comments</comments>
		<pubDate>Mon, 15 Feb 2010 11:38:16 +0000</pubDate>
		<dc:creator>Benjamin Schröter</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[coding]]></category>
		<category><![CDATA[dotnet]]></category>
		<category><![CDATA[dotnet3.5]]></category>
		<category><![CDATA[wpf]]></category>

		<guid isPermaLink="false">http://www.ticklishtechs.net/2010/02/15/a-change-event-for-dependency-properties/</guid>
		<description><![CDATA[WPF comes with Dependency Properties and everybody using WPF will know about these new kind of properties. When you define your own Dependency Properties in your own class you can pretty easy add a property change event handler: public int MyProperty { get { return (int)GetValue(MyPropertyProperty); } set { SetValue(MyPropertyProperty, value); } } public static [...]]]></description>
			<content:encoded><![CDATA[<p>WPF comes with Dependency Properties and everybody using WPF will know about these new kind of properties. When you define your own Dependency Properties in your own class you can pretty easy add a property change event handler:</p>
<pre class="code"><span style="color: blue;">public int </span>MyProperty
{
    <span style="color: blue;">get </span>{ <span style="color: blue;">return </span>(<span style="color: blue;">int</span>)GetValue(MyPropertyProperty); }
    <span style="color: blue;">set </span>{ SetValue(MyPropertyProperty, <span style="color: blue;">value</span>); }
}
<span style="color: blue;">public static readonly </span><span style="color: #2b91af;">DependencyProperty </span>MyPropertyProperty =
    <span style="color: #2b91af;">DependencyProperty</span>.Register(<span style="color: #a31515;">"MyProperty"</span>,
                        <span style="color: blue;">typeof</span>(<span style="color: blue;">int</span>),
                        <span style="color: blue;">typeof</span>(<span style="color: #2b91af;">MainWindow</span>),
                        <span style="color: blue;">new </span><span style="color: #2b91af;">UIPropertyMetadata</span>(0,
                            <strong>MyPropertyvalueChangeCallback</strong>));

<span style="color: blue;">private static void </span><strong>MyPropertyvalueChangeCallback</strong>
                        (<span style="color: #2b91af;">DependencyObject </span>d,
                         <span style="color: #2b91af;">DependencyPropertyChangedEventArgs </span>e)
{
}</pre>
<p>But how to add such a event handler to an already existing Dependency Property or somewhere else then in the defining class? E.g. to an property of a WPF-Control that was not build by you. Take a standard WPF-TextBox; both the <code>Text</code> and the <code>FontSize</code> properties are Dependency Properties but the <code>TextBox</code>-class only provides a change event for the <code>Text</code>-property. Nevertheless you can get a change event for any Dependency Property:</p>
<pre class="code"><span style="color: #2b91af;">DependencyPropertyDescriptor </span>dpd =
    <span style="color: #2b91af;">DependencyPropertyDescriptor</span>.FromProperty
        (<span style="color: #2b91af;">Control</span>.FontSizeProperty, <span style="color: blue;">typeof </span>(<span style="color: #2b91af;">TextBox</span>));
dpd.AddValueChanged(someTextBox, SomeTextBoxFontSizeChanged);</pre>
<p>Every time the FontSizeProperty on the instance <code>someTextBox</code> changes the given method is called. It’s that easy and you can implement this code everywhere not only within the class that defines the property.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.ticklishtechs.net/2010/02/15/a-change-event-for-dependency-properties/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Shell-Lib reloaded: Another OS, another bug.</title>
		<link>http://www.ticklishtechs.net/2010/01/10/shell-lib-reloaded-another-os-another-bug/</link>
		<comments>http://www.ticklishtechs.net/2010/01/10/shell-lib-reloaded-another-os-another-bug/#comments</comments>
		<pubDate>Sun, 10 Jan 2010 14:38:06 +0000</pubDate>
		<dc:creator>Wolfram Bernhardt</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[coding]]></category>
		<category><![CDATA[dotnet]]></category>
		<category><![CDATA[marshalling]]></category>
		<category><![CDATA[windows7]]></category>

		<guid isPermaLink="false">http://www.ticklishtechs.net/2010/01/10/shell-lib-reloaded-another-os-another-bug/</guid>
		<description><![CDATA[Some time ago we blogged about a nifty little .net assembly that enables you to access the basic Windows shell operations in shell32.dll . You may want to do so especially in Win7 because your file operations integrate with the fancy Win7 dialogs, the flashing progress bar etc. The problem we blogged about in the [...]]]></description>
			<content:encoded><![CDATA[<p>Some time ago we blogged about a nifty little .net assembly that enables you to access the basic <a href="http://www.ticklishtechs.net/2007/09/02/windows-shell32dll-shfileoperation-marshalling-and-hnamemappings/">Windows shell operations</a> in shell32.dll . You may want to do so especially in Win7 because your file operations integrate with the fancy Win7 dialogs, the flashing progress bar etc. </p>
<p>The problem we blogged about in <a href="http://www.ticklishtechs.net/2007/09/02/windows-shell32dll-shfileoperation-marshalling-and-hnamemappings/">the former post</a> was a missing &quot;Pack&quot;-instruction in the marshalling-description of a structure. I guess we didn&#8217;t test it with WinXP64&#8230; but some days ago we tests it with Win7/64 and it failed. We figured out that we introduced a new bug that occurred on 64 bit machines only. After some more testing we found out that: </p>
<ul>
<li>The original code (without Pack-value) crashes on 32 bit machines (as described in the former post). </li>
<li>The original code (without Pack-value) works fine on 64 bit machines (but we don&#8217;t think the original developer had 64 bits 7 years ago <img src='http://www.ticklishtechs.net/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' />  ). </li>
<li>Our fixed code (with Pack=2) works fine on 32 bit machines. </li>
<li>Our fixed code (with Pack=2) crashes on 64 bit machines. </li>
</ul>
<p>It seems that the &quot;SHFILEOPSTRUCT&quot; structure in shell32.dll has different layouts in Win7/64 and Win7/32. I guess the guys at MS aim for performance and tell the compiler to optimize. The compiler optimizes by assuming the optimal Pack-value, which usually is the byte-width of the processor; 4 for 32bit, 8 for 64bit. </p>
<h3>What effect does the Pack-value have at all?</h3>
<p>The &quot;Pack&quot;-value controls the alignment of the starting addresses of each single member of a structure (often called &quot;offset&quot;). </p>
<p>Let&#8217;s say you have this struct: </p>
<p> <code>
<p>struct MammaMia      <br />{       <br />&#160;&#160;&#160; public int16 sweet16;       <br />&#160;&#160;&#160; public byte bite;       <br />&#160;&#160;&#160; public string tanga;       <br />} </p>
<p> </code>
<p>Usually you don&#8217;t care for the exact way your data is stored in memory, but when you pass it from .NET to the Win-API you have to make sure Win-API receives and returns exactly the right format. This process is called &quot;Marshalling&quot;. </p>
<p>One crucial instruction for doing so is the StructLayout attribute. </p>
<p> <code>
<p>[StructLayout(LayoutKind.Sequential, Pack = 1)]      <br />struct MammaMia       <br />{       <br />&#160;&#160;&#160; public int16 sweet16;       <br />&#160;&#160;&#160; public byte bite;       <br />&#160;&#160;&#160; public string tanga;       <br />} </p>
<p> </code>
<p>(Note: There are a lot more options for the StructLayout attribute and a lot more attributes that help you at marshalling.) </p>
<p><strong>LayoutKind.Sequential</strong> means that your data is represented in memory in the same order as you declared it: First &quot;sweet16&quot;, than &quot;bite&quot; and then &quot;tanga&quot;. </p>
<p><strong>Pack=1</strong> tells .NET that every byte can be the starting point of the next member. So .NET produces this structure in memory:</p>
<p><strong></strong></p>
<table border="0" cellspacing="0" cellpadding="2" width="197">
<tbody>
<tr>
<td valign="top" width="50"><strong>Pack=1</strong></td>
<td valign="top" width="145">&#160;</td>
</tr>
<tr>
<td valign="top" width="50">byte</td>
<td valign="top" width="145">data</td>
</tr>
<tr>
<td valign="top" width="50">0</td>
<td valign="top" width="145">sweet16</td>
</tr>
<tr>
<td valign="top" width="50">1</td>
<td valign="top" width="145">sweet16</td>
</tr>
<tr>
<td valign="top" width="50">2</td>
<td valign="top" width="145">bite</td>
</tr>
<tr>
<td valign="top" width="50">3</td>
<td valign="top" width="145">tanga</td>
</tr>
<tr>
<td valign="top" width="50">4</td>
<td valign="top" width="145">tanga</td>
</tr>
<tr>
<td valign="top" width="50">…</td>
<td valign="top" width="145">…</td>
</tr>
<tr>
<td valign="top" width="50">20</td>
<td valign="top" width="145">last character of tanga</td>
</tr>
</tbody>
</table>
<p>&#160;</p>
<p>&#160;</p>
<p>Now <strong>Pack=2</strong> makes sure that only every 2nd byte can be the starting point of the next member. That leads &#8211; of course &#8211; to unused bytes in memory: </p>
<table border="0" cellspacing="0" cellpadding="2" width="197">
<tbody>
<tr>
<td valign="top" width="50"><strong>Pack=2</strong></td>
<td valign="top" width="145">&#160;</td>
</tr>
<tr>
<td valign="top" width="50">byte</td>
<td valign="top" width="145">data</td>
</tr>
<tr>
<td valign="top" width="50">0</td>
<td valign="top" width="145">sweet16</td>
</tr>
<tr>
<td valign="top" width="50">1</td>
<td valign="top" width="145">sweet16</td>
</tr>
<tr>
<td valign="top" width="50">2</td>
<td valign="top" width="145">bite</td>
</tr>
<tr>
<td valign="top" width="50">3</td>
<td valign="top" width="145">??? (unused)</td>
</tr>
<tr>
<td valign="top" width="50">4</td>
<td valign="top" width="145">tanga</td>
</tr>
<tr>
<td valign="top" width="50">5</td>
<td valign="top" width="145">tanga</td>
</tr>
<tr>
<td valign="top" width="50">…</td>
<td valign="top" width="145">…</td>
</tr>
<tr>
<td valign="top" width="50">21</td>
<td valign="top" width="145">last character of tanga</td>
</tr>
</tbody>
</table>
<p>&#160;</p>
<p>&#160;</p>
<p>The higher the Pack-value, the more unused bytes you get:</p>
<table border="0" cellspacing="0" cellpadding="2" width="197">
<tbody>
<tr>
<td valign="top" width="50"><strong>Pack=4</strong></td>
<td valign="top" width="145">&#160;</td>
</tr>
<tr>
<td valign="top" width="50">byte</td>
<td valign="top" width="145">data</td>
</tr>
<tr>
<td valign="top" width="50">0</td>
<td valign="top" width="145">sweet16</td>
</tr>
<tr>
<td valign="top" width="50">1</td>
<td valign="top" width="145">sweet16</td>
</tr>
<tr>
<td valign="top" width="50">2</td>
<td valign="top" width="145">??? (unused)</td>
</tr>
<tr>
<td valign="top" width="50">3</td>
<td valign="top" width="145">??? (unused)</td>
</tr>
<tr>
<td valign="top" width="50">4</td>
<td valign="top" width="145">bite</td>
</tr>
<tr>
<td valign="top" width="50">5</td>
<td valign="top" width="145">??? (unused)</td>
</tr>
<tr>
<td valign="top" width="50">6</td>
<td valign="top" width="145">??? (unused)</td>
</tr>
<tr>
<td valign="top" width="50">7</td>
<td valign="top" width="145">??? (unused)</td>
</tr>
<tr>
<td valign="top" width="50">8</td>
<td valign="top" width="145">tanga</td>
</tr>
<tr>
<td valign="top" width="50">9</td>
<td valign="top" width="145">tanga</td>
</tr>
<tr>
<td valign="top" width="50">…</td>
<td valign="top" width="145">…</td>
</tr>
<tr>
<td valign="top" width="50">25</td>
<td valign="top" width="145">last character of tanga</td>
</tr>
</tbody>
</table>
<p>&#160;</p>
<p>Is this a waste of memory? Sure. But processors can access those addresses a bit faster than other addresses. So it&#8217;s an performance/memory tradeoff. </p>
<p>After some more testing, I figured out that the correct Pack-value for Win7/64 is 8, while the correct Pack-value for Win7/32 is 2 (see former post). Why 2? I&#8217;d expect 4 here. I don&#8217;t know and Microsoft wouldn&#8217;t provide the source code I guess.    <br />Maybe in former Windows version they preferred a middle-course between performance and saving memory. </p>
<h3>The simple solution</h3>
<p>Now it was obvious how to make die ShellLib-assembly work with 32 and 64bit: Check what machine we run on and use a different marshalling. Since I had to declare different structs here, the major code is copying data back and forth, not very interesting.</p>
<p>The only interesting part here is: How do you check on what kind of machine you run? I was looking for some property at System.Environment, but didn’t find anything. Then <a href="http://blog.aheil.de/">Andreas</a> pointed me to <a href="http://blogs.msdn.com/kstanton/archive/2004/04/20/116923.aspx">this</a> post and the solution is too simple to cross one’s mind:</p>
<p>“Just do a <strong>IntPtr.Size</strong> (static method) and since IntPtr is designed to be an integer whose size is platform specific, it will be <strong>8 if you are on a 64-bit machine and 4 if you are on a 32-bit machine</strong>.“</p>
<p>You can find more information and our fixed code soon at the <a href="http://www.codeproject.com/KB/shell/csdoesshell2.aspx">codeproject.com</a> .</p>
<h3>Epilog</h3>
<p>You can also do the marshalling all by yourself, starting with memory allocation and ending with freeing memory, just like in the old times. But this is another story and will be told later. </p>
<p>Maybe.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.ticklishtechs.net/2010/01/10/shell-lib-reloaded-another-os-another-bug/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to get a IWin32Window from a WPF Window?</title>
		<link>http://www.ticklishtechs.net/2009/12/22/how-to-get-a-iwin32window-from-a-wpf-window/</link>
		<comments>http://www.ticklishtechs.net/2009/12/22/how-to-get-a-iwin32window-from-a-wpf-window/#comments</comments>
		<pubDate>Tue, 22 Dec 2009 12:53:34 +0000</pubDate>
		<dc:creator>Benjamin Schröter</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[dotnet]]></category>
		<category><![CDATA[wpf]]></category>

		<guid isPermaLink="false">http://www.ticklishtechs.net/2009/12/22/how-to-get-a-iwin32window-from-a-wpf-window/</guid>
		<description><![CDATA[When building applications that mix WPF and Winforms windows (e.g. because you are using a Winforms dialog within a WPF application) you will sometimes need a System.Windows.Forms.IWin32Window interface from an WPF System.Windows.Window. This will be useful when using the WinForms OpenFileDialog and wanting to provide a parent window to the ShowDialog() method that only accepts [...]]]></description>
			<content:encoded><![CDATA[<p>When building applications that mix WPF and Winforms windows (e.g. because you are using a Winforms dialog within a WPF application) you will sometimes need a <a title="IWin32Window Interface" href="http://msdn2.microsoft.com/215475ec.aspx">System.Windows.Forms.IWin32Window</a> interface from an WPF <a title="Window Class" href="http://msdn2.microsoft.com/ms590112.aspx">System.Windows.Window</a>. This will be useful when using the WinForms <a title="OpenFileDialog Class" href="http://msdn2.microsoft.com/y1kh29w3.aspx">OpenFileDialog</a> and wanting to provide a parent window to the <a title="OpenFileDialog..::.ShowDialog Method " href="http://msdn2.microsoft.com/bb552427.aspx">ShowDialog()</a> method that only accepts IWin32Window as parent.</p>
<p>The <code>IWin32Window</code> interface declares only one read-only property named <code>Handle</code> that must be provided by the WPF Window. </p>
<h3>Implementing the Interface</h3>
<p>It is very simple to just add this interface to an existing WPF Window and implementing the single property:</p>
<pre class="code"><span style="color: blue">public partial class </span><span style="color: #2b91af">Window1 </span>: <span style="color: #2b91af">Window</span>, <span style="color: #2b91af">IWin32Window
</span>{
   <span style="color: blue">public </span><span style="color: #2b91af">IntPtr </span>Handle
   {
      <span style="color: blue">get
      </span>{
         <span style="color: blue">var </span>interopHelper = <span style="color: blue">new </span><span style="color: #2b91af">WindowInteropHelper</span>(<span style="color: blue">this</span>);
         <span style="color: blue">return </span>interopHelper.Handle;
      }
   }
}</pre>
<p>&#160;</p>
<h3>Using a wrapper class</h3>
<p>It does not look as a very good solution to add such an interface to each and every <code>Window</code> in you whole application only to be able to be the parent of a dialog. So instead of implementing the interface directly you could build a wrapper class that implements this interface and use this wrapper when opening a dialog:</p>
<pre class="code"><span style="color: blue">public class </span><span style="color: #2b91af">Wpf32Window </span>: <span style="color: #2b91af">IWin32Window
</span>{
    <span style="color: blue">public </span><span style="color: #2b91af">IntPtr </span>Handle { <span style="color: blue">get</span>; <span style="color: blue">private set</span>; }

    <span style="color: blue">public </span>Wpf32Window(<span style="color: #2b91af">Window </span>wpfWindow)
    {
        Handle = <span style="color: blue">new </span><span style="color: #2b91af">WindowInteropHelper</span>(wpfWindow).Handle;
    }
}</pre>
<p>Opening the dialog will now look like: </p>
<pre class="code">d.ShowDialog( <span style="color: blue">new </span><span style="color: #2b91af">Wpf32Window</span>(<span style="color: blue">this</span>) );</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<h3>The grand solution to this problem</h3>
<p>I like the wrapper solution more than implementing an interface to each and every window but I do not like the changed <code>ShowDialog()</code> call. It just does not look natural any more. To solve this I created an extension Method to be used with the wrapper class:</p>
<pre class="code"><span style="color: blue">public static class </span><span style="color: #2b91af">CommonDialogExtensions
</span>{
    <span style="color: blue">public static </span><span style="color: #2b91af">DialogResult </span>ShowDialog
                               (<span style="color: blue">this </span><span style="color: #2b91af">CommonDialog </span>dialog,
                                     <span style="color: #2b91af">Window </span>parent)
    {
        <span style="color: blue">return </span>dialog.ShowDialog(<span style="color: blue">new </span><span style="color: #2b91af">Wpf32Window</span>(parent));
    }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a>Now the call to open a WinForms dialog with an WPF parent looks as it should look like:</p>
<pre class="code">d.ShowDialog(<span style="color: blue">this</span>);</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.ticklishtechs.net/2009/12/22/how-to-get-a-iwin32window-from-a-wpf-window/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Isn&#8217;t one OpenFileDialog enough?</title>
		<link>http://www.ticklishtechs.net/2009/12/22/isnt-one-openfiledialog-enough/</link>
		<comments>http://www.ticklishtechs.net/2009/12/22/isnt-one-openfiledialog-enough/#comments</comments>
		<pubDate>Tue, 22 Dec 2009 12:53:25 +0000</pubDate>
		<dc:creator>Benjamin Schröter</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[dotnet]]></category>
		<category><![CDATA[wpf]]></category>

		<guid isPermaLink="false">http://www.ticklishtechs.net/2009/12/22/isnt-one-openfiledialog-enough/</guid>
		<description><![CDATA[In fact one OpenFileDialog is enough but the .net framework provides two of them: System.Windows.Forms.OpenFileDialog in System.Windows.Forms.dll Microsoft.Win32.OpenFileDialog in PresentationFramework.dll (that is WPF) With such a setup one would use the first for WinForms applications and the second for WPF apps. In fact if you create a WPF application and just type in OpenFileDialog you [...]]]></description>
			<content:encoded><![CDATA[<p>In fact one OpenFileDialog is enough but the .net framework provides two of them:</p>
<ol>
<li><a title="OpenFileDialog Class" href="http://msdn2.microsoft.com/y1kh29w3.aspx">System.Windows.Forms.OpenFileDialog</a> in System.Windows.Forms.dll </li>
<li><a title="OpenFileDialog Class" href="http://msdn2.microsoft.com/ms653561.aspx">Microsoft.Win32.OpenFileDialog</a> in PresentationFramework.dll (that is WPF) </li>
</ol>
<p>With such a setup one would use the first for WinForms applications and the second for WPF apps. In fact if you create a WPF application and just type in <code>OpenFileDialog</code> you will get number 2.</p>
<p>But the 2nd one (even if it is part of the newer part of the framework) is an old dialog where the 1st will use the new and shiny Windows 7 dialog on Win7. Just look at the following screenshots.</p>
<p><a href="http://www.ticklishtechs.net/wp-content/uploads/2009/12/a.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="a" border="0" alt="a" src="http://www.ticklishtechs.net/wp-content/uploads/2009/12/a_thumb.png" width="404" height="337" /></a> </p>
<p><a href="http://www.ticklishtechs.net/wp-content/uploads/2009/12/b.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="b" border="0" alt="b" src="http://www.ticklishtechs.net/wp-content/uploads/2009/12/b_thumb.png" width="404" height="301" /></a> </p>
<p>Only the first class uses the Windows 7 dialog and comes with proper support for Libraries etc. Even if the second shows the Libraries in its left part it does not fully support this new Windows 7 feature.</p>
<p>I have no idea why the WPF class uses the old windows API but it does. For best compatibility with all Windows versions (including 7) you should always use the Winforms Dialog even when building WPF apps! It does not hurt to reference the System.Windows.Forms.dll (it is installed an every machine running the .net framework) and you can use that dialog from WPF without any trouble.</p>
<p>You should only know about one little disadvantage when using the WinForms dialog. It only accepts WinForms as a parent window no WPF windows. To overcome this limitation please read my other article about the <code>IWin32Window</code> interface and how to implement / provide it in WPF at <a title="http://www.ticklishtechs.net/2009/12/22/how-to-get-a-iwin32window-from-a-wpf-window/" href="http://www.ticklishtechs.net/2009/12/22/how-to-get-a-iwin32window-from-a-wpf-window/">http://www.ticklishtechs.net/2009/12/22/how-to-get-a-iwin32window-from-a-wpf-window/</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.ticklishtechs.net/2009/12/22/isnt-one-openfiledialog-enough/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Hunting high and low</title>
		<link>http://www.ticklishtechs.net/2009/07/14/hunting-high-and-low/</link>
		<comments>http://www.ticklishtechs.net/2009/07/14/hunting-high-and-low/#comments</comments>
		<pubDate>Tue, 14 Jul 2009 11:48:31 +0000</pubDate>
		<dc:creator>Wolfram Bernhardt</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[algorithm]]></category>
		<category><![CDATA[coding]]></category>
		<category><![CDATA[dotnet]]></category>
		<category><![CDATA[maths]]></category>

		<guid isPermaLink="false">http://www.ticklishtechs.net/2009/07/14/hunting-high-and-low/</guid>
		<description><![CDATA[Here is a nice little challenge, Benjamin came up with some months ago: &#8220;From a list of numbers find the smallest and the largest one &#8211; but do not use more than 1,5 comparisons per number.&#8221; Dear reader: Try it! The solution is simple, straight forward and very nice. And I didn&#8217;t find it. I [...]]]></description>
			<content:encoded><![CDATA[<p>Here is a nice little challenge, Benjamin came up with some months ago: &#8220;From a list of numbers find the smallest and the largest one &#8211; but do not use more than 1,5 comparisons per number.&#8221;</p>
<p>Dear reader: Try it!</p>
<p>The solution is simple, straight forward and very nice. And I didn&#8217;t find it.</p>
<p>I found something else. My approach was to look at the largest-number-so-far (max) and the smallest-number-so-far (min) as the boundaries of a region. A number outside this region must be larger than max or smaller than min and causes that boundary to change.</p>
<p>To check if a number (a) was outside that region a little computation came to my mind:</p>
<pre class="code">check = (max - a)*(min - a);</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>You would expect n to be smaller than max, so (max-n) should be positive.</p>
<p>You would expect n to be larger than min, so (n-min) should be positive, too.</p>
<p>Two positive numbers multiplied result in a positive number again.</p>
<p>So, if n was outside the boundaries, <font size="2" face="Courier New">check</font> would become negative. I only had to check which boundary was exceeded and that&#8217;s it:</p>
<pre class="code"><span style="color: blue">if (</span>check &lt; 0)
<span style="color: blue">    if </span>(a &gt; max)
        max = a;
    <span style="color: blue">else
        </span>min = a;</pre>
<p>Using this approach the number of comparisons&nbsp; converges to 1 when the length of the list grows. So I found a solution that is way better than 1,5 comparisons per number, didn&#8217;t I?</p>
<h3>Boooooh</h3>
<p>No, I didn&#8217;t. I cheated. In fact&nbsp; <font size="2" face="Courier New">(max-a)</font> and <font size="2" face="Courier New">(min-a)</font> are comparisons, they just don&#8217;t use &gt; or &lt;.</p>
<p>(Actually it&#8217;s the other way around: To compute &lt; or &gt; most processors do a subtraction and compare the result to 0.)</p>
<p>So &#8211; if you count the subtractions as well you get 3+ comparisons per number&#8230;</p>
<p>The intended solution to the challenge (and the code you should provide in your exam) is:</p>
<pre class="code">a = list[count++];
b = list[count++];

<span style="color: blue">if </span>(a&lt;b)
{
    <span style="color: blue">if </span>(a&lt;min) min = a;
    <span style="color: blue">if </span>(b&gt;max) max = b;
}
<span style="color: blue">else
</span>{
    <span style="color: blue">if </span>(b &lt; min) min = b;
    <span style="color: blue">if </span>(a &gt; max) max = a;
}
</pre>
<h3>&nbsp;</h3>
<h3>So &#8211; what&#8217;s the point of this post?</h3>
<p>The point is: My silly approach can be faster than the standard solution. Depending on the type and range of the numbers in the list calculating and probing <font size="2" face="Courier New">check</font> needs less time than the comparisons in the standard solution.</p>
<p>It may not be much, but sometimes small advantages matter.&nbsp; For example: For an integer-list of length 10^8 with values from -10.000 to 10.000 my approach is 0.02 seconds faster (on my current laptop). And has less code.</p>
<p>So if you feel like using it &#8211; I won&#8217;t charge you.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.ticklishtechs.net/2009/07/14/hunting-high-and-low/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Access to modified closure</title>
		<link>http://www.ticklishtechs.net/2009/04/10/access-to-modified-closure/</link>
		<comments>http://www.ticklishtechs.net/2009/04/10/access-to-modified-closure/#comments</comments>
		<pubDate>Fri, 10 Apr 2009 09:32:35 +0000</pubDate>
		<dc:creator>Benjamin Schröter</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[coding]]></category>
		<category><![CDATA[dotnet]]></category>
		<category><![CDATA[dotnet3.5]]></category>

		<guid isPermaLink="false">http://www.ticklishtechs.net/2009/04/10/access-to-modified-closure/</guid>
		<description><![CDATA[Imaging a small C# winform app with just one ListBox and the following code: private void Form1_Load(object sender, EventArgs e) { for (int i = 0; i &#60; 5; i++) { Thread t = new Thread(() =&#62; AddToListbox(i)); t.Start(); } } private void AddToListbox(int i) { if (this.InvokeRequired) this.Invoke(new Action&#60;int&#62;(AddToListbox), i); else this.listBox1.Items.Add(i); } A [...]]]></description>
			<content:encoded><![CDATA[<p>Imaging a small C# winform app with just one ListBox and the following code:</p>
<pre class="code"><span style="color: blue">private void </span>Form1_Load(<span style="color: blue">object </span>sender, <span style="color: #2b91af">EventArgs </span>e)
{
    <span style="color: blue">for </span>(<span style="color: blue">int </span>i = 0; i &lt; 5; i++)
    {
        <span style="color: #2b91af">Thread </span>t = <span style="color: blue">new </span><span style="color: #2b91af">Thread</span>(() =&gt; AddToListbox(i));
        t.Start();
    }
}

<span style="color: blue">private void </span>AddToListbox(<span style="color: blue">int </span>i)
{
    <span style="color: blue">if </span>(<span style="color: blue">this</span>.InvokeRequired)
        <span style="color: blue">this</span>.Invoke(<span style="color: blue">new </span><span style="color: #2b91af">Action</span>&lt;<span style="color: blue">int</span>&gt;(AddToListbox), i);
    <span style="color: blue">else
        this</span>.listBox1.Items.Add(i);
}</pre>
<p><a href="http://11011.net/software/vspaste"></a>A simple loop iterating over the numbers from 0 to 4 and adding these values asynchronous to a ListBox. What do you expect? I expected the numbers from 0 to 4 shown in the ListBox but in any random order since I do not control the threads in any way.</p>
<p><a href="http://www.ticklishtechs.net/wp-content/uploads/2009/04/a.png"><img style="border-right: 0px; border-top: 0px; display: inline; border-left: 0px; border-bottom: 0px" title="2 - 3 - 4 - 5 - 5" src="http://www.ticklishtechs.net/wp-content/uploads/2009/04/a-thumb.png" border="0" alt="2 - 3 - 4 - 5 - 5" width="183" height="154" /></a> <a href="http://www.ticklishtechs.net/wp-content/uploads/2009/04/b.png"><img style="border-right: 0px; border-top: 0px; display: inline; border-left: 0px; border-bottom: 0px" title="4 - 2 -  2 - 4 - 5" src="http://www.ticklishtechs.net/wp-content/uploads/2009/04/b-thumb.png" border="0" alt="4 - 2 -  2 - 4 - 5" width="183" height="154" /></a></p>
<p>I didn’t expect any number to appear multiple times and I’m totally surprised to  see the number 5!</p>
<p>But <a href="http://www.jetbrains.com/resharper/">ReSharper</a> gave me a hint that I often saw but never understood:</p>
<p><a href="http://www.ticklishtechs.net/wp-content/uploads/2009/04/u.png"><img style="border-right: 0px; border-top: 0px; display: inline; border-left: 0px; border-bottom: 0px" title="&quot;Access to modified closure&quot; by  R#" src="http://www.ticklishtechs.net/wp-content/uploads/2009/04/u-thumb.png" border="0" alt="&quot;Access to modified closure&quot; by  R#" width="480" height="158" /></a></p>
<h3>So what’s going on?</h3>
<p>I use the syntax of an Lambda expression instead of a regular function call (e.g. using the ThreadStart class and a delegate). This Lambda expression is not evaluated until the thread uses it. And by this time, the loop can be in its next iteration. If the loop is already finished <code>i</code> will be 5.</p>
<p>That is exactly what R# tries to tell me: “Hey, you are accessing here a variable but change it later on. Maybe that is not a good idea.”. – It isn’t.</p>
<h3>The solution</h3>
<p>Just make a copy of <code>i</code> before passing it into the expression. This copy must be a private copy that will not be changed later. The easiest way to do so is declaring a variable inside the body of the loop. In every iteration of the loop a new integer will be created on the stack and the Lambda expression will access this one.</p>
<pre class="code"><span style="color: blue">for </span>(<span style="color: blue">int </span>i = 0; i &lt; 5; i++)
{
    <strong><span style="color: blue">int </span>copy = i;</strong>
    <span style="color: #2b91af">Thread </span>t = <span style="color: blue">new </span><span style="color: #2b91af">Thread</span>(() =&gt; AddToListbox(<strong>copy</strong>));
    t.Start();
}</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.ticklishtechs.net/2009/04/10/access-to-modified-closure/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

