<?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>Xster.net &#187; multithreading</title>
	<atom:link href="http://tech.xster.net/tag/multithreading/feed/" rel="self" type="application/rss+xml" />
	<link>http://tech.xster.net</link>
	<description>Never relearn twice</description>
	<lastBuildDate>Fri, 20 Jan 2012 21:11:29 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Multi-Threading and Delegates Tutorial in VB .NET</title>
		<link>http://tech.xster.net/tips/multi-threading-in-vb-net/</link>
		<comments>http://tech.xster.net/tips/multi-threading-in-vb-net/#comments</comments>
		<pubDate>Sat, 24 Oct 2009 23:14:34 +0000</pubDate>
		<dc:creator>xiao</dc:creator>
				<category><![CDATA[Tips]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[callback]]></category>
		<category><![CDATA[delegate]]></category>
		<category><![CDATA[invoke]]></category>
		<category><![CDATA[Microsoft]]></category>
		<category><![CDATA[multithreading]]></category>
		<category><![CDATA[parameter]]></category>
		<category><![CDATA[thread]]></category>
		<category><![CDATA[vb]]></category>

		<guid isPermaLink="false">http://tech.xster.net/?p=139</guid>
		<description><![CDATA[This guide will show you everything you need to create a non-GUI multi-threaded application in VB .NET. There are 2 ways of using multi-threading in VB .NET. First by making use of delegates which I will explain here. And second by programming the threads manually (not actually more complicated). Using delegates, .NET helps simplify the entire process of using [...]]]></description>
			<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><p>This guide will show you everything you need to create a non-GUI multi-threaded application in VB .NET.</p>
<p>There are 2 ways of using multi-threading in VB .NET. First by making use of delegates which I will explain here. And second by programming the threads manually (not actually more complicated).</p>
<p>Using delegates, .NET helps simplify the entire process of using a separate thread and saves you from having to manage the parameter passing, result retrieving and timing issues.<span id="more-139"></span></p>
<p>First to simply call a method on a separate thread with a parameter</p>

<div class="wp_syntax"><div class="code"><pre class="vb" style="font-family:monospace;">Delegate <span style="color: #E56717; font-weight: bold;">Function</span> MyDelegate(<span style="color: #151B8D; font-weight: bold;">ByVal</span> text <span style="color: #151B8D; font-weight: bold;">as</span> <span style="color: #F660AB; font-weight: bold;">String</span>) <span style="color: #151B8D; font-weight: bold;">as</span> <span style="color: #F660AB; font-weight: bold;">String</span>
&nbsp;
<span style="color: #E56717; font-weight: bold;">Function</span> PrintStuff(<span style="color: #151B8D; font-weight: bold;">ByVal</span> text <span style="color: #151B8D; font-weight: bold;">as</span> <span style="color: #F660AB; font-weight: bold;">String</span>) <span style="color: #151B8D; font-weight: bold;">as</span> <span style="color: #F660AB; font-weight: bold;">String</span>
    Console.WriteLine(text)
    Thread.Sleep(5000)
    Return <span style="color: #800000;">&quot;Success&quot;</span>
<span style="color: #8D38C9; font-weight: bold;">End</span> <span style="color: #E56717; font-weight: bold;">Function</span>
&nbsp;
<span style="color: #E56717; font-weight: bold;">Sub</span> Main()
    <span style="color: #151B8D; font-weight: bold;">Dim</span> d <span style="color: #151B8D; font-weight: bold;">as</span> MyDelegate = AddressOf PrintStuff
    d.BeginInvoke(<span style="color: #800000;">&quot;hello world&quot;</span>, <span style="color: #00C2FF; font-weight: bold;">Nothing</span>, <span style="color: #00C2FF; font-weight: bold;">Nothing</span>)
    <span style="color: #008000;">'I can do more stuff here
</span><span style="color: #8D38C9; font-weight: bold;">End</span> <span style="color: #E56717; font-weight: bold;">Sub</span></pre></div></div>

<p>Here we have a Main thread and a second thread to print some stuff. Also, a delegate with the same signature as the function we want to run (PrintStuff) already exists. Very simply, the Main thread creates a delegate that points to PrintsStuff and calls for the delegate to start executing PrintStuff on a separate thread. A parameter is passed to PrintStuff in the process and Main can continue working while PrintStuff is busy.</p>
<p>Now suppose you want to know when PrintStuff finishes because you want the result &#8220;Success&#8221;. We can do this by the use of a callback function.</p>
<p>First, we create the callback function</p>

<div class="wp_syntax"><div class="code"><pre class="vb" style="font-family:monospace;"><span style="color: #E56717; font-weight: bold;">Sub</span> MyCallback(<span style="color: #151B8D; font-weight: bold;">ByVal</span> result <span style="color: #151B8D; font-weight: bold;">as</span> IAsyncResult)
    Console.WriteLine(<span style="color: #800000;">&quot;Now I know PrintStuff finished&quot;</span>)
<span style="color: #8D38C9; font-weight: bold;">End</span> <span style="color: #E56717; font-weight: bold;">Sub</span></pre></div></div>

<p>Then we make sure the callback function gets called by changing the previous BeginInvoke command to</p>

<div class="wp_syntax"><div class="code"><pre class="vb" style="font-family:monospace;">d.BeginInvoke(<span style="color: #800000;">&quot;hello world&quot;</span>, <span style="color: #E56717; font-weight: bold;">New</span> AsyncCallback(AddressOf MyCallback), <span style="color: #00C2FF; font-weight: bold;">Nothing</span>)</pre></div></div>

<p>In other words, the before last parameter (depending on how many parameters your MyDelegate is supposed to take, since they come in front) is where you specify your callback function. Now MyCallback will be called when PrintStuff is done (ie after about 5 seconds)</p>
<p>Now we need MyCallback function to actually read the return of PrintStuff (&#8220;Success&#8221;). It is contained in the IAsyncResult.</p>

<div class="wp_syntax"><div class="code"><pre class="vb" style="font-family:monospace;"><span style="color: #E56717; font-weight: bold;">Sub</span> MyCallback(<span style="color: #151B8D; font-weight: bold;">ByVal</span> result <span style="color: #151B8D; font-weight: bold;">as</span> IAsyncResult)
    Console.WriteLine(<span style="color: #800000;">&quot;Now I know PrintStuff finished&quot;</span>)
    <span style="color: #151B8D; font-weight: bold;">Dim</span> resultClass = CType(result, AsyncResult)
    <span style="color: #151B8D; font-weight: bold;">Dim</span> d <span style="color: #151B8D; font-weight: bold;">as</span> MyDelegate = CType(resultClass.AsyncDelegate, MyDelegate)
    Console.WriteLine(<span style="color: #800000;">&quot;And I also know that the result is: &quot;</span> &amp; d.EndInvoke(result))
<span style="color: #8D38C9; font-weight: bold;">End</span> <span style="color: #E56717; font-weight: bold;">Sub</span></pre></div></div>

<p>In other words， (instance of MyDelegate).EndInvoke will give you the return of PrintStuff. You could have simply called it in your Main instead of MyCallback, but then Main will remain on that line until PrintStuff reaches its Return line, defeating the whole purpose of multi-threading. When you use EndInvoke in the callback function, you are guaranteed that PrintStuff has already reached its Return line and you simply have to retrieve the result.</p>
<p>For multi-threading applications involving GUI elements, check by <a href="http://tech.xster.net/tips/invoke-ui-changes-across-threads-on-vb-net/">other tutorial</a> to see how to avoid illegal cross-thread operations.</p>
<div class="shr-publisher-139"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><div style="clear: both; min-height: 1px; height: 3px; width: 100%;"></div><div class='shareaholic-like-buttonset' style='float:none;height:30px;'><a class='shareaholic-googleplusone' data-shr_size='medium' data-shr_count='true' data-shr_href='http%3A%2F%2Ftech.xster.net%2Ftips%2Fmulti-threading-in-vb-net%2F' data-shr_title='Multi-Threading+and+Delegates+Tutorial+in+VB+.NET'></a><a class='shareaholic-tweetbutton' data-shr_count='none' data-shr_href='http%3A%2F%2Ftech.xster.net%2Ftips%2Fmulti-threading-in-vb-net%2F' data-shr_title='Multi-Threading+and+Delegates+Tutorial+in+VB+.NET'></a></div><div style="clear: both; min-height: 1px; height: 3px; width: 100%;"></div><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://tech.xster.net/tips/multi-threading-in-vb-net/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Invoke UI Changes Across Threads on VB .Net</title>
		<link>http://tech.xster.net/tips/invoke-ui-changes-across-threads-on-vb-net/</link>
		<comments>http://tech.xster.net/tips/invoke-ui-changes-across-threads-on-vb-net/#comments</comments>
		<pubDate>Sat, 09 May 2009 04:22:58 +0000</pubDate>
		<dc:creator>xiao</dc:creator>
				<category><![CDATA[Tips]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[Access]]></category>
		<category><![CDATA[addressof]]></category>
		<category><![CDATA[cross]]></category>
		<category><![CDATA[delegate]]></category>
		<category><![CDATA[invoke]]></category>
		<category><![CDATA[Microsoft]]></category>
		<category><![CDATA[multithreading]]></category>
		<category><![CDATA[thread]]></category>
		<category><![CDATA[vb]]></category>
		<category><![CDATA[visual basic]]></category>

		<guid isPermaLink="false">http://tech.xster.net/?p=72</guid>
		<description><![CDATA[I need to do this all the time and don&#8217;t have the best memory in the world. Today, I decided that I looked this up one too many times so here&#8217;s my solution to this multithreading problem: The Problem: You try to modify UI components created in one thread in another thread. In VB, you [...]]]></description>
			<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><p>I need to do this all the time and don&#8217;t have the best memory in the world. Today, I decided that I looked this up one too many times so here&#8217;s my solution to this multithreading problem:</p>
<p><strong>The Problem:</strong></p>
<p>You try to modify UI components created in one thread in another thread. In VB, you can only make UI changes on the same thread that created it so you get a nice &#8220;Cross thread operation not valid&#8221; exception.</p>
<p>Here&#8217;s the wrong code:</p>

<div class="wp_syntax"><div class="code"><pre class="vb" style="font-family:monospace;">thread = <span style="color: #E56717; font-weight: bold;">New</span> System.Threading.Thread(AddressOf DoStuff)
thread.Start()</pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="vb" style="font-family:monospace;"><span style="color: #E56717; font-weight: bold;">Private</span> <span style="color: #E56717; font-weight: bold;">Sub</span> DoStuff()
    <span style="color: #008000;">'error occurs here'
</span>    Me.Text = <span style="color: #800000;">&quot;Stuff&quot;</span>
<span style="color: #8D38C9; font-weight: bold;">End</span> <span style="color: #E56717; font-weight: bold;">Sub</span></pre></div></div>

<p><strong><span id="more-72"></span>The Solution:</strong></p>
<p>If you&#8217;re super lazy or you&#8217;re very sure of what your code is going to do, you can simply disable the exception with:</p>

<div class="wp_syntax"><div class="code"><pre class="vb" style="font-family:monospace;"><span style="color: #E56717; font-weight: bold;">Private</span> <span style="color: #E56717; font-weight: bold;">Sub</span> DoStuff()
    Me.CheckForIllegalCrossThreadCalls = <span style="color: #00C2FF; font-weight: bold;">False</span>
    Me.Text = <span style="color: #800000;">&quot;Stuff&quot;</span>
<span style="color: #8D38C9; font-weight: bold;">End</span> <span style="color: #E56717; font-weight: bold;">Sub</span></pre></div></div>

<p>This, of course, doesn&#8217;t prevent your code from making a mess. To do it properly, you need a delegate:</p>

<div class="wp_syntax"><div class="code"><pre class="vb" style="font-family:monospace;">thread = <span style="color: #E56717; font-weight: bold;">New</span> System.Threading.Thread(AddressOf DoStuff)
thread.Start()</pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="vb" style="font-family:monospace;"><span style="color: #E56717; font-weight: bold;">Private</span> Delegate <span style="color: #E56717; font-weight: bold;">Sub</span> DoStuffDelegate()
<span style="color: #E56717; font-weight: bold;">Private</span> <span style="color: #E56717; font-weight: bold;">Sub</span> DoStuff()
    <span style="color: #8D38C9; font-weight: bold;">If</span> Me.InvokeRequired <span style="color: #8D38C9; font-weight: bold;">Then</span>
        Me.Invoke(<span style="color: #E56717; font-weight: bold;">New</span> DoStuffDelegate(AddressOf DoStuff))
    <span style="color: #8D38C9; font-weight: bold;">Else</span>
        Me.Text = <span style="color: #800000;">&quot;Stuff&quot;</span>
    <span style="color: #8D38C9; font-weight: bold;">End</span> <span style="color: #8D38C9; font-weight: bold;">If</span>
<span style="color: #8D38C9; font-weight: bold;">End</span> <span style="color: #E56717; font-weight: bold;">Sub</span></pre></div></div>

<p>Wildly simple right?</p>
<p>To understand what the code does, you need to understand what Invoke() does. It can be confusing to google Invoke() because Delegates and Controls have different implementations of Invoke(). In this case, we&#8217;re calling Invoke on a subclass of Control. That causes the method on the second thread which is going through DoStuff() to run a method on the first thread (which created the UI element).</p>
<p>Now if you need parameters, here&#8217;s another example where &#8220;ReallyLongProcess&#8221; is a subroutine that raises an event &#8220;Done&#8221; with a parameter &#8220;success&#8221;</p>

<div class="wp_syntax"><div class="code"><pre class="vb" style="font-family:monospace;">AddHandler Me.Done, AddressOf WorkFinished
thread = <span style="color: #E56717; font-weight: bold;">new</span> System.Threading.Thread(AddressOf ReallyLongProcess)
thread.Start()</pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="vb" style="font-family:monospace;"><span style="color: #E56717; font-weight: bold;">Private</span> Delegate <span style="color: #E56717; font-weight: bold;">Sub</span> DoStuffDelegate(<span style="color: #151B8D; font-weight: bold;">ByRef</span> success <span style="color: #151B8D; font-weight: bold;">as</span> <span style="color: #F660AB; font-weight: bold;">Boolean</span>)
<span style="color: #E56717; font-weight: bold;">Private</span> <span style="color: #E56717; font-weight: bold;">Sub</span> DoStuff(<span style="color: #151B8D; font-weight: bold;">ByRef</span> success <span style="color: #151B8D; font-weight: bold;">as</span> <span style="color: #F660AB; font-weight: bold;">Boolean</span>)
    <span style="color: #8D38C9; font-weight: bold;">If</span> Me.InvokeRequired <span style="color: #8D38C9; font-weight: bold;">Then</span>
        Me.Invoke(<span style="color: #E56717; font-weight: bold;">New</span> DoStuffDelegate(AddressOf DoStuff), success)
    <span style="color: #8D38C9; font-weight: bold;">Else</span>
        <span style="color: #8D38C9; font-weight: bold;">If</span> success <span style="color: #8D38C9; font-weight: bold;">Then</span>
            <span style="color: #008000;">'do stuff
</span>        <span style="color: #8D38C9; font-weight: bold;">Else</span>
            <span style="color: #008000;">'do stuff
</span>        <span style="color: #8D38C9; font-weight: bold;">End</span> <span style="color: #8D38C9; font-weight: bold;">If</span>
    <span style="color: #8D38C9; font-weight: bold;">End</span> <span style="color: #8D38C9; font-weight: bold;">If</span>
<span style="color: #8D38C9; font-weight: bold;">End</span> <span style="color: #E56717; font-weight: bold;">Sub</span></pre></div></div>

<div class="shr-publisher-72"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><div style="clear: both; min-height: 1px; height: 3px; width: 100%;"></div><div class='shareaholic-like-buttonset' style='float:none;height:30px;'><a class='shareaholic-googleplusone' data-shr_size='medium' data-shr_count='true' data-shr_href='http%3A%2F%2Ftech.xster.net%2Ftips%2Finvoke-ui-changes-across-threads-on-vb-net%2F' data-shr_title='Invoke+UI+Changes+Across+Threads+on+VB+.Net'></a><a class='shareaholic-tweetbutton' data-shr_count='none' data-shr_href='http%3A%2F%2Ftech.xster.net%2Ftips%2Finvoke-ui-changes-across-threads-on-vb-net%2F' data-shr_title='Invoke+UI+Changes+Across+Threads+on+VB+.Net'></a></div><div style="clear: both; min-height: 1px; height: 3px; width: 100%;"></div><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://tech.xster.net/tips/invoke-ui-changes-across-threads-on-vb-net/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

