<?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>Code Reference &#187; BackgroundWorker</title>
	<atom:link href="http://sullivan.net/blog/tag/backgroundworker/feed/" rel="self" type="application/rss+xml" />
	<link>http://sullivan.net/blog</link>
	<description>A collection of code for my reference (and perhaps other people too)</description>
	<lastBuildDate>Wed, 25 Jan 2012 17:53:32 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Background worker Argument and Result</title>
		<link>http://sullivan.net/blog/2009/10/background-worker-argument-and-result/</link>
		<comments>http://sullivan.net/blog/2009/10/background-worker-argument-and-result/#comments</comments>
		<pubDate>Tue, 13 Oct 2009 10:42:14 +0000</pubDate>
		<dc:creator>Darren</dc:creator>
				<category><![CDATA[c#]]></category>
		<category><![CDATA[BackgroundWorker]]></category>
		<category><![CDATA[Threads]]></category>

		<guid isPermaLink="false">http://sullivan.net/blog/?p=202</guid>
		<description><![CDATA[Because the background worker runs in a different thread, it cannot interact easily with the main UI thread. It is good to keep in mind: * The DoWork method is in it's own thread. * The RunWorkerCompleted method is in the main UI thread. Passing into and out of the background worker is simple. When [...]]]></description>
			<content:encoded><![CDATA[<p>Because the background worker runs in a different thread, it cannot interact easily with the main UI thread. </p>
<p>It is good to keep in mind:<br />
* The DoWork method is in it's own thread.<br />
* The RunWorkerCompleted method is in the main UI thread.</p>
<p>Passing into and out of the background worker is simple.<br />
When you start the worker, you can easily add an object as such:</p>
<pre class="brush: c#">
try
{
     bgWorker.RunWorkerAsync(myObject);
}
catch (Exception ex)
{
     throw;
}
</pre>
<p>In the backgound worker method you get the object as the routed event argument 'Argument'.<br />
Pass something back thru the 'Result' arguement.</p>
<pre class="brush: c#">
private void bgWorker_DoWork(object sender, DoWorkEventArgs e)
{
     MyObject myObject= e.Argument as MyObject;

     // do something

     // Put the result in e.Result
     e.Result = myNewObject;
}
</pre>
<p>You can get the result in the RunWorkerCompleted method:</p>
<pre class="brush: c#">
private void bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
     MyObject myNewObject = e.Result;

     // do something else
}
</pre>
<p>It is all very simple.</p>
<p>You can also loop thru an object in the RunWorkerCompleted method and have the results display as they finish:</p>
<pre class="brush: c#">
int counter = myObjectList.Count();

private void bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
     MyObject myNewObject = e.Result;
     if (myNewObject != null)
     {
          UpdateTheUI(myNewObject);
          System.Windows.Forms.Application.DoEvents(); // forces a UI update
     }

     if (counter &lt; myObjectList.Count())
     {
          MyObject o = myObjectList[counter];
          bgWorker.RunWorkerAsync(o);
          counter++;
     }
     else
     {
          bgWorker.RunWorkerCompleted -= new RunWorkerCompletedEventHandler(bgWorker_RunWorkerCompleted);
          bgWorker.DoWork -= new DoWorkEventHandler(bgWorker_DoWork);
     }
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://sullivan.net/blog/2009/10/background-worker-argument-and-result/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Background workers</title>
		<link>http://sullivan.net/blog/2009/07/background-workers/</link>
		<comments>http://sullivan.net/blog/2009/07/background-workers/#comments</comments>
		<pubDate>Tue, 28 Jul 2009 08:45:46 +0000</pubDate>
		<dc:creator>Darren</dc:creator>
				<category><![CDATA[c#]]></category>
		<category><![CDATA[BackgroundWorker]]></category>
		<category><![CDATA[Threads]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://sullivan.net/blog/?p=45</guid>
		<description><![CDATA[Background workers are VERY useful. They keep you to do run intensive process without locking up your UI. Again, a picture (or code) is worth a thousand words... // Declare your background worker private BackgroundWorker bgWorker = new BackgroundWorker(); // In the constructor or some other method you must initialize things private void StartBackgroundWorker() { [...]]]></description>
			<content:encoded><![CDATA[<p>Background workers are VERY useful. They keep you to do run intensive process without locking up your UI.</p>
<p>Again, a picture (or code) is worth a thousand words... </p>
<pre class="brush: c#">
// Declare your background worker
private BackgroundWorker bgWorker = new BackgroundWorker();

// In the constructor or some other method you must initialize things
private void StartBackgroundWorker()
{
   // When the background worker finishes, this event is triggered
   bgWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgWorker_RunWorkerCompleted);

   // When the background worker is started, this event is triggered
   bgWorker.DoWork += new DoWorkEventHandler(bgWorker_DoWork);

   // If the background worker is canceled, this event is triggered
   bgWorker.WorkerSupportsCancellation = true;

   // Create a button someplace to stop the background worker
   btnStop.Click += new RoutedEventHandler(btnStop_Clicked);
   // start the background worker
   try
   {
      bgWorker.RunWorkerAsync();
   }
   catch (Exception ex) { // do something }
}

private void btnStop_Clicked(object sender, RoutedEventArgs e)
{
   // Unregister the events or they may not get garbage collected
   btnStop.Click -= new RoutedEventHandler(btnStop_Clicked);
   bgWorker.RunWorkerCompleted -= new RunWorkerCompletedEventHandler(bgWorker_RunWorkerCompleted);
   bgWorker.DoWork -= new DoWorkEventHandler(bgWorker_DoWork);

   // stop the background worker
   bgWorker.CancelAsync();
}

private void bgWorker_DoWork(object sender, DoWorkEventArgs e)
{
   // Start the process
   // This will be done in a seperate thread
}

private void bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
   if (e.Cancelled)
   {
       return;
   }
   if (e.Error != null)
   {
       return;
   }

   // show the user the results of the process that was running... or whatever you want to do

   // Unregister the events or they may not get garbage collected
   btnStop.Click -= new RoutedEventHandler(btnStop_Clicked);
   bgWorker.RunWorkerCompleted -= new RunWorkerCompletedEventHandler(bgWorker_RunWorkerCompleted);
   bgWorker.DoWork -= new DoWorkEventHandler(bgWorker_DoWork);
}
</pre>
<p>That is all there is to it! Simple? Sure it is.</p>
<p>However, there are some things you should know.</p>
<p>* If you cancel the background worker, they process is not stopped. It will continue running until it finishes. Canceling simple disconnects that thread and stops listening to it.<br />
* If you want to stop that thread, then you should have that thread often check for the cancel event and stop itself if it is TRUE.<br />
* If you start and cancel a process too many time, you can will ecounter problems. You should develope a way to prevent this.</p>
]]></content:encoded>
			<wfw:commentRss>http://sullivan.net/blog/2009/07/background-workers/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

