Parallel Extensions to the .NET Framework ForumDiscuss and ask questions about Microsoft Parallel Extensions to the .NET Framework -- Including usage, performance, scaling, future development, and more.© 2009 Microsoft Corporation. All rights reserved.Wed, 25 Nov 2009 18:28:49 Z1fdb607c-fe5f-45a1-8980-14b7e06196b0http://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/2840267d-e2e2-4b8b-aa81-a33a5cbbde63http://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/2840267d-e2e2-4b8b-aa81-a33a5cbbde63John_GPThttp://social.msdn.microsoft.com/Profile/en-US/?user=John_GPTExample to speed up Sample GenerationHi, wondering if anyone out there can give me an example of how they would parallelize this function.... It should be doable.... i just cant crack it..<br/><br/><span style="font-family:Courier New;font-size:x-small"><span style="font-family:Courier New;font-size:x-small"><span style="font-family:Courier New;font-size:x-small"><span style="font-family:Courier New;font-size:x-small"> <p> </p> <pre lang=x-vbnet> Public Function RandomArray(ByVal iSamples As Integer, ByVal dMu As Double, ByVal dSigma As Double) As Double() Dim oRnd As New Random Dim dRandomVariate As Double Dim dSample As Double Dim lstSamples As New Generic.List(Of Double) For i As Integer = 0 To iSamples - 1 dRandomVariate = Math.Sqrt(-2 * Math.Log(oRnd.NextDouble)) * Math.Sin(2 * Math.PI * oRnd.NextDouble) dSample = Math.Exp(dMu + dSigma * dRandomVariate) lstSamples.Add(dSample) Next Return lstSamples.ToArray End Function</pre> </span></span></span></span>Wed, 25 Nov 2009 09:25:43 Z2009-11-25T18:28:49Zhttp://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/e5b992ac-61dc-4a40-a8bd-c4fdbfcd4119http://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/e5b992ac-61dc-4a40-a8bd-c4fdbfcd4119rohits79http://social.msdn.microsoft.com/Profile/en-US/?user=rohits79Application, cores and threadsApologies for asking a real stupid question but it's been boiling for some time.<br/> <br/> Question: So far I've been writing single prototype to see it perform better using multi-core/TPL, I was wondering if all major application/services (say 50 or more) on my box start using core-thread-affinity/concurrency what would be the impact in terms of overall performance versus if so many applications do not use or say a very limited number of applications use concurrency i.e. the way it is today?. Has anyone studied the performance difference between the two? In terms of battery life I am sure concurrency would make cores suck lot more power? <br/> <br/> Also though it would defeat the purpose of having concurrency in first place, but can we have a system wide policy where we can specify to use only X number of cores for concurrency. Also can we some how be biased on applications which start recently or are in the main view to get more number of cores as compared to the service which has been running for say last week?Tue, 24 Nov 2009 07:19:28 Z2009-11-25T02:35:53Zhttp://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/52144b2b-bc56-449c-8129-a2dbe48efc0chttp://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/52144b2b-bc56-449c-8129-a2dbe48efc0cphilippe lombaershttp://social.msdn.microsoft.com/Profile/en-US/?user=philippe%20lombaersProducer/Consumer pattern questionHello,<br/><br/>Here is my code :<br/><br/> <pre lang="x-c#">BlockingCollection&lt;long&gt; bc = new BlockingCollection&lt;long&gt;(2); var producer = Task.Factory.StartNew(() =&gt; { for (long i = 0; i &lt; 10; i++) { bc.Add(i); } bc.CompleteAdding(); }); var consumer = Task.Factory.StartNew(() =&gt; { Parallel.ForEach&lt;long&gt;(bc.GetConsumingEnumerable(), id =&gt; { Console.WriteLine(id); Thread.Sleep(2000); }); }); consumer.Wait(); <br/></pre> The consumer is not working as I would like because it empties the collection too fast and the producer continues to add elements.<br/>Like this I lose the benefit of boundedcapacity = 2.<br/>I'd like the consumer to create 2 background tasks and wait for completion before letting the producer adding new elements.<br/><br/>Thanks.<hr class="sig">philippeTue, 24 Nov 2009 09:29:30 Z2009-11-24T21:08:36Zhttp://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/50690d28-6dab-4f8f-89a3-d62ef1b34a9fhttp://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/50690d28-6dab-4f8f-89a3-d62ef1b34a9fRagowithttp://social.msdn.microsoft.com/Profile/en-US/?user=RagowitNested Parallel.ForEach ?I have been reading <a href="http://msdn.microsoft.com/en-us/library/dd460720(VS.100).aspx">http://msdn.microsoft.com/en-us/library/dd460720(VS.100).aspx</a> and found it very interesting, but I have a question. <div><br/></div> <div>What if my code looks something like this:</div> <div> <pre lang="x-c#">Parallel.ForEach(arrayA, currentA =&gt; { foreach (int currentB in arrayB) { foreach (int currentC in arrayC) { // do something here } } } );</pre> Do I only need the Parallel.ForEach on the first loop (like the code above) or on all foreach-statements?</div>Mon, 23 Nov 2009 17:22:54 Z2009-11-23T20:23:41Zhttp://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/cda43742-3bbc-4dc8-85a4-75001495f032http://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/cda43742-3bbc-4dc8-85a4-75001495f032David Parrhttp://social.msdn.microsoft.com/Profile/en-US/?user=David%20ParrWould you please post the ProfilerExamples.csproj that you demonstrated at PDC '09?<p>Would you please post the ProfilerExamples.csproj that you demonstrated at PDC '09? (is not part of ParallelProgrammingSamples_Beta2.zip)<br/><br/>Thank you.<br/><br/>p.s. - Stephen T. - fantastic presentation; i wish that i had seen it first in '08 or been paying attention on channel 9 - will follow from now on.</p>Sun, 22 Nov 2009 14:36:14 Z2009-11-23T22:55:01Zhttp://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/38d7a436-e1d1-4af8-8525-791ebeed9663http://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/38d7a436-e1d1-4af8-8525-791ebeed9663GrahamBLGhttp://social.msdn.microsoft.com/Profile/en-US/?user=GrahamBLGUpdating a progress bar from inside a Parallel.ForHi,<br><br>I'm using the CTP for .NET 3.5 in VS2008<br><br>I have 2 problems.<br><br>1/<br>I have a custom Control with a ProgressBar and a processing Engine object.<br><br>At the heart of the Engine object is a Parellel.For 'loop'. <br><br>I wish to step the ProgressBar from within the loop and am failing to do so usefully.<br><br>I first tried firing an event from inside the loop which was received by the control which then updated the progressbar ( see code below). This failed to return and the whole loop hung.<br><br>private delegate void ThreadSafedelegate();<br><br>                ThreadSafedelegate update = delegate()<br>                    {<br>                        progressBar.Value++;                        <br>                        Application.DoEvents();<br>                    };<br><br>                if (InvokeRequired)<br>                    Invoke(update);<br>                else<br>                    update();<br>                System.Diagnostics.Trace.WriteLine(&quot;After update&quot;); // this line never reached<br>           <br>Using Parallel.Invoke(Step) fared no better.<br><br>I then used Task.Create(() =&gt; Step(), TaskCreationOptions.Detached) to fire the event. This rather wonderfully ran all the processing loops and only afterwards fired all the step events!<br><br>I've considered passing the control to the engine and then calling the control step function directly, but I can't see this helping as the problem appears to be in dealing with the control UI than with firing the event.<br><br>Any suggestions about how I could go about this?<br><br>2/ in a similar situation to the above I have an abort button on the control and I use that to set a flag which is examined in the processing engine Parallel.For 'loop' to call state.Stop(). All well and good, but when the loop is running no button clicks are processed by the form. When I insert an Application.DoEvents() in the loop, the behaviour doesn't change except that the engine eventually crashes with the following message:-<br><br>System.InvalidOperationException was unhandled<br>  Message=&quot;The Undo operation encountered a context that is different from what was applied in the corresponding Set operation. The possible cause is that a context was Set on the thread and not reverted(undone).&quot;<br>  Source=&quot;mscorlib&quot;<br>  StackTrace:<br>       at System.Threading.SynchronizationContextSwitcher.Undo()<br>       at System.Threading.ExecutionContextSwitcher.Undo()<br>       at System.Threading.ExecutionContext.runFinallyCode(Object userData, Boolean exceptionThrown)<br>       at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteBackoutCodeHelper(Object backoutCode, Object userData, Boolean exceptionThrown)<br>       at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)<br>       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)<br>       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)<br>       at System.Threading.Tasks.Task.Execute(Boolean stolen)<br>       at System.Threading.Tasks.TaskBase.InvokeStolen()<br>       at System.Threading.ConcurrencyScheduler.InternalContext.Dispatch()<br>       at System.Threading.ConcurrencyScheduler.ThreadInternalContext.ThreadStartBridge(IntPtr dummy)<br>  InnerException: <br><br>Any suggestions?<br><br>Cheers<br>Graham<br><br><br> Fri, 06 Feb 2009 19:40:51 Z2009-11-21T03:42:10Zhttp://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/2674bad7-c3ff-475e-a2fc-71ed1e21a1c7http://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/2674bad7-c3ff-475e-a2fc-71ed1e21a1c7Ed Essey - MSFThttp://social.msdn.microsoft.com/Profile/en-US/?user=Ed%20Essey%20-%20MSFTReleased! Parallel Extensions to the .NET Framework 3.5 June 2008 CTP<span style="font-family:Arial;font-size:x-small"> <p align=left> </p> <p>Parallel Extensions to the .NET Framework simplifies development by providing library-based support for introducing concurrency into applications written with any .NET language, including C# and Visual Basic. It includes the Task Parallel Library (TPL), which provides imperative data and task parallelism; Parallel LINQ (PLINQ), which provides declarative data parallelism; and all new Coordination Data Structures (CDS), which provide support for work coordination and managing shared state.</p> <p> </p> <p align=left>In addition to CDS, this upgrade provides several improvements, including a new scheduler that is more robust, efficient, and scalable. TPL also exposes new functionality, including methods for continuations. PLINQ now runs on top of TPL, clarifies order-preservation, and provides several new operators.</p> <ul> <li> <div><a href="http://blogs.msdn.com/pfxteam/archive/2008/06/02/8567802.aspx">Released! Parallel Extensions to the .NET Framework June 2008 CTP</a></div> </li> <li> <div><a href="http://blogs.msdn.com/pfxteam/archive/2008/06/02/8567093.aspx">What's New in the June 2008 CTP of Parallel Extensions</a></div> </li> <li> <div> <div><a href="http://blogs.msdn.com/pfxteam/archive/2008/06/02/8567816.aspx">Known Issues in the June 2008 CTP of Parallel Extensions</a></div> </div> </li> <li><a href="http://blogs.msdn.com/pfxteam/archive/2008/06/02/8567825.aspx">On Achieving Perfection –or– Why We Love Your Feedback (and Why You Can Love Giving It)</a> </li> </ul> <p align=left>Thanks,</p> <p align=left>Ed</p> <p align=left><a title="http://www.microsoft.com/downloads/details.aspx?FamilyId=348F73FD-593D-4B3C-B055-694C50D2B0F3&amp;displaylang=en" href="http://www.microsoft.com/downloads/details.aspx?FamilyId=348F73FD-593D-4B3C-B055-694C50D2B0F3&amp;displaylang=en"></a> </p> </span>Mon, 02 Jun 2008 17:01:45 Z2009-11-20T21:57:53Zhttp://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/1ca54699-f682-44ec-af94-41dd423f869dhttp://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/1ca54699-f682-44ec-af94-41dd423f869dfoobar101http://social.msdn.microsoft.com/Profile/en-US/?user=foobar101documentation on Parallel Programming with .NET 4 Beta 2 SamplesWhere is it?<br/> <br/> Thank you.<br/>Thu, 19 Nov 2009 00:23:42 Z2009-11-19T15:18:42Zhttp://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/312edb09-cef1-4e42-9de6-139dc3561f03http://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/312edb09-cef1-4e42-9de6-139dc3561f03rohits79http://social.msdn.microsoft.com/Profile/en-US/?user=rohits79Why can't I pass ParallelOptions/TokenSource as a function member to my Task function?<div>Do we always need to make CancellationTokenSource a static or a member variable to access from the parallel function (Test) in the below code for example? It would have been better if we could pass CancellationTokenSource as a function parameter like parallelloopstate that way we can create static libraries that would consist of only core parallel logic? Please correct me if i have overlooked at something?</div> <div><br/></div> <div> <div>using System;</div> <div>using System.Threading;</div> <div>using System.Threading.Tasks;</div> <div><br/></div> <div>namespace ConsoleApplication1</div> <div>{</div> <div>    class Program</div> <div>    {</div> <div>        static ParallelOptions po = new ParallelOptions();</div> <div>        static CancellationTokenSource cts = new CancellationTokenSource();</div> <div>            </div> <div>        static void Main(string[] args)</div> <div>        {</div> <div>            </div> <div>            try</div> <div>            {</div> <div>                ParallelLoopResult result = Parallel.For(1, 100000, po, Test);</div> <div>            }</div> <div>            catch(AggregateException exception)</div> <div>            {</div> <div>                //handle code here</div> <div>            }</div> <div>            </div> <div>           </div> <div>            Console.ReadKey();</div> <div>        }</div> <div><br/></div> <div>        public static void Test(int number, ParallelLoopState loopState)</div> <div>        {</div> <div>            if (cts.IsCancellationRequested) // cts is accessed here because it's static member variable, why can't we pass this as a function variable member?</div> <div>            {</div> <div>                Console.WriteLine(&quot;returning&quot;);</div> <div>                cts.Token.ThrowIfCancellationRequested();</div> <div>            }</div> <div>          </div> <div>        }</div> <div>    }</div> <div>}</div> <div><br/></div> </div> <div><br/></div> <div><br/></div>Thu, 19 Nov 2009 08:00:14 Z2009-11-19T08:54:53Zhttp://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/39685059-fb7a-483c-97f1-450a930073f5http://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/39685059-fb7a-483c-97f1-450a930073f5Kamran Shahidhttp://social.msdn.microsoft.com/Profile/en-US/?user=Kamran%20ShahidParallel computing in .net 3.5 Sp1 to read large chunk of textfile into objectsI have a more then 100 meg of file.I am reading the file and loading it into my objects line by line. I am now investigating how can i improve it.Can I use parallel programming in .net 3.5 Sp1 to improve my time My current code is<br/> Also I completely new in this.<br/> Let me know if I need to install any thing on development machine and on the deployment server or not<br/> <br/> My current code for loading the file is<br/> <br/> <pre lang="x-c#">private void LoadObjects() { Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); StreamReader reader = File.OpenText(@&quot;c:\TestFile.txt&quot;); StringBuilder line = new StringBuilder(reader.ReadLine()); BookObject objBook = null; List&lt;BookObject&gt; objBookList = new List&lt;BookObject&gt;(); while (line != null &amp;&amp; line.ToString().Length &gt; 0) { objBook = new BookObject(); objBook.Property1 = line.ToString().Substring(0, 27); objBook.Property2 = line.ToString().Substring(28, 5); objBook.Property3 = line.ToString().Substring(53, 8); objBook.Property4 = line.ToString().Substring(62, 8); objBookList.Add(objBook); line = new StringBuilder(reader.ReadLine()); } reader.Close(); stopWatch.Stop(); TimeSpan ts = stopWatch.Elapsed; MessageBox.Show(&quot;Loaded in [&quot; + ts.Milliseconds.ToString() + &quot; milliseconds or &quot; + ts.Seconds.ToString() + &quot; Seconds&quot;); }</pre><hr class="sig">Kamran Shahid Senior Software Engineer/Analyst (MCP,MCAD,MCSD.NET,MCTS,MCPD.net[web])Tue, 17 Nov 2009 13:21:27 Z2009-11-19T08:34:49Zhttp://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/4ad3f36d-cc05-412a-a43b-953a72e068d6http://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/4ad3f36d-cc05-412a-a43b-953a72e068d6Vladimir_MShttp://social.msdn.microsoft.com/Profile/en-US/?user=Vladimir_MSWhat is a best way to do a cancellable sleep for subsecond period of time?<p>Hi,<br/><br/>Here is my scenario - I need tasks that perform work lazily - after a small delay (~100ms) and only if it is not cancelled by that time. <br/>Basically we have situations where we know that there is a work to be done (user input, other assync changes...), but want to do it only if nothing happens in the next 100ms.<br/><br/>I see two possible solutions - start task with<br/><br/><span style="font-family:Consolas;font-size:x-small">1) <br/>Sleep(DELAY)<br/><span style="font-family:Consolas;font-size:x-small"><span style="font-family:Consolas;font-size:x-small">cancellationToken.ThrowIfCancellationRequested()</span></span><br/></span><br/>(we will hog the thread for the time of DELAY)<br/><br/><span style="font-family:Consolas;font-size:x-small">or </span><br/><br/>2) <br/><span style="font-family:Consolas;font-size:x-small"><span style="font-family:Consolas;font-size:x-small">Threading.</span></span><span style="font-family:Consolas;color:#2b91af;font-size:x-small"><span style="font-family:Consolas;color:#2b91af;font-size:x-small"><span style="font-family:Consolas;color:#2b91af;font-size:x-small">SpinWait</span></span></span><span style="font-family:Consolas;font-size:x-small"><span style="font-family:Consolas;font-size:x-small">.SpinUntil(</span></span><span style="font-family:Consolas;color:#0000ff;font-size:x-small"><span style="font-family:Consolas;color:#0000ff;font-size:x-small"><span style="font-family:Consolas;color:#0000ff;font-size:x-small">Function</span></span></span><span style="font-family:Consolas;font-size:x-small"><span style="font-family:Consolas;font-size:x-small">() cancellationToken.IsCancellationRequested, DELAY)<br/>cancellationToken.ThrowIfCancellationRequested() <p>(spinning may waste some CPU resources)<br/><br/><br/>It is not very important to have precise timings. I am just wondering what would be the best way to sleep for subsecond period when running in a Task? Or what other factors I should consider?<br/><br/>Thanks,<br/>Vladimir<br/><br/></p> </span></span></p>Wed, 18 Nov 2009 00:00:22 Z2009-11-21T05:58:37Zhttp://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/1167234a-02a6-4069-8126-31ca92a7283bhttp://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/1167234a-02a6-4069-8126-31ca92a7283bShamroxhttp://social.msdn.microsoft.com/Profile/en-US/?user=ShamroxTask ComunicationI am a web developer and very often we will start a task &quot;thread&quot; and have the ui watch it till it finishes we also have other tasks talk to each other. I guess my question is there code show how Tasks can communicate together?Wed, 18 Nov 2009 19:22:14 Z2009-11-21T05:58:51Zhttp://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/f1f949f8-5eed-499b-b68b-df80c1f431a7http://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/f1f949f8-5eed-499b-b68b-df80c1f431a7Alexander Petrovhttp://social.msdn.microsoft.com/Profile/en-US/?user=Alexander%20PetrovHow to Set TaskManager to PLINQ Hello,<br><br>in early version of PFX we have such overloaded verstion of PLINQ's AsParallel extenstion method:<br><a href="http://my.safaribooksonline.com/9780321434821/app02lev1sec2">http://my.safaribooksonline.com/9780321434821/app02lev1sec2</a><br><br>public static IParallelEnumerable&lt;TSource&gt; AsParallel&lt;TSource&gt;(<br>    this IEnumerable&lt;TSource&gt; source,<br>    TaskManager taskManager<br>);<br><br>But in June08 CTP as far as I can understand we lose that ability.<br>How to set users' TaskManager to PLINQ ?<br><br>Thank youThu, 26 Feb 2009 08:35:14 Z2009-11-17T10:45:16Zhttp://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/7b3a42e5-4ebf-405a-8ee6-bcd2f0214f85http://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/7b3a42e5-4ebf-405a-8ee6-bcd2f0214f85matt.garvenhttp://social.msdn.microsoft.com/Profile/en-US/?user=matt.garvenTask Dispose best practice?When working with Tasks, especially continuations and nested tasks (attached or unattached), what would be the recommended approach for disposing the tasks?<br/><br/>e.g. in a situation something along these lines...<br/><br/> <div style="background-color:white;color:black"> <pre>Task.Factory.StartNew(() =&gt; { <span style="color:green">// do things</span> }).ContinueWith(t =&gt; { <span style="color:green">// do things</span> Task.Factory.StartNew(() =&gt; { <span style="color:green">// do things</span> }); })<br/>.ContinueWith(t =&gt; { <span style="color:green">// do things</span> }); </pre> </div> <br/>Thanks,<br/>MattMon, 16 Nov 2009 07:05:36 Z2009-11-17T10:18:38Zhttp://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/b6dfbbcd-07a8-4e73-8f81-807e97e83836http://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/b6dfbbcd-07a8-4e73-8f81-807e97e83836Bijanhttp://social.msdn.microsoft.com/Profile/en-US/?user=BijanF# & parallel performance<p class=MsoNormal style="margin:0cm 0cm 10pt"><span style="line-height:115%;font-family:'Verdana','sans-serif';color:black;font-size:8pt">I was playing with &quot;Samples for Parallel Programming with the .NET Framework 4 (<a href="http://code.msdn.microsoft.com/ParExtSamples">http://code.msdn.microsoft.com/ParExtSamples</a>)&quot; and just tested the release version of Raytracer_CSharp and Raytracer_FSharp. The speed of both were the same in single threaded mode and interestingly the memory usage of F#version was less than the C# version. But when I switched to parallel mode, the C# version was faster than the F# version. I had a look at the CPU consumption and found out that the C# version was consuming 92% to 96% of CPU time while the F# version about 82% to 87%. Any explanation for this behavior?</span></p> <p class=MsoNormal style="margin:0cm 0cm 10pt"><span style="line-height:115%;font-family:'Verdana','sans-serif';color:black;font-size:8pt">Thanks,<br/></span><span style="line-height:115%;font-family:'Verdana','sans-serif';color:black;font-size:8pt">Bijan</span></p>Wed, 04 Nov 2009 19:00:32 Z2009-11-10T00:54:57Zhttp://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/f56880f1-c17e-49aa-a47d-d9a86cd97666http://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/f56880f1-c17e-49aa-a47d-d9a86cd97666Varun_Devhttp://social.msdn.microsoft.com/Profile/en-US/?user=Varun_DevParallel.For problem<span style="font-size:x-small"><span style="font-size:x-small"> <p> Hello All</p> </span></span> <p><span style="color:#2b91af;font-size:x-small"><span style="color:#2b91af;font-size:x-small">I am trying to create an application in which there are around 10 dll's each working sequentially. Now I want to make the app multi threaded . the application checks if it can find name of machine through interface and if it does it starts doing different tests on machine(computer). So , suppose listbox have 3 computer names , it will make entry in 1st table say id=1, name=server 1and move to check drivers on machine ....<br/>to make it multithreaded this is what I am trying ......<br/><br/><br/></span></span></p> <span style="font-size:x-small"><span style="color:#0000ff;font-size:x-small"><span style="font-size:x-small"> <pre>Parallel.For(0, listBox1.Items.Count - 1, delegate(int i) gbl.strComputer = listBox1.Items[i].ToString(); { Logs.Logging(gbl.logFilePath, &quot; &quot;, true); Logs.Logging(gbl.logFilePath, &quot;Establishing Connection to.......&quot; + gbl.strComputer, true); Conn.fnConnect(gbl.strComputer, gbl.logFilePath); if (returnConnect == 0) // if able to connect start pulling the information { id = Machine_Information.InsertServerInformation(gbl.strComputer, gbl.logFilePath); if (id == 0) { Logs.Logging(gbl.logFilePath, &quot;Processing FAILED on &quot; + gbl.strComputer, true); Logs.Logging(gbl.logFilePath, &quot; &quot;, true); } else { Driver Information Logs.Logging(gbl.logFilePath, &quot;Task 4 STARTED : Getting Driver Information&quot;, true); Driver_Information.InsertDriverInformation(gbl.logFilePath, gbl.strComputer, id); if (driverInfoCollector) Logs.Logging(gbl.logFilePath, &quot;Task 4 Finished : Driver Information inserted in Driver Table&quot;, true); else { Logs.Logging(gbl.logFilePath, &quot;Task 4 Failed. Some or All drivers are not written to database. &quot;, true); #endregion } </pre> <br/><br/></span></span> <p>Problem is After adding Parallel.for in the code , it inserts bad information. Sometimes , its just entering same information sometimes its not entering anything . When i try to step through the code , it waits at some lines indefinitely and next time it steps through ssamr line in very fast. <br/><br/>PLease let me know , what is the procedure of using this library  to do something like :<br/><br/>if(listbox.item.count &gt;0)<br/>{<br/>put information in 1st table <br/><br/>if(information inserted in 1st table )<br/>{<br/>use primary key of 1st table that is &quot;id&quot; as input in second dll and put information in 2nd table <br/>use primary key of 1st table that is &quot;id&quot; as input in third dll and put information in 3rd table <br/>use primary key of 1st table that is &quot;id&quot; as input in fourth dll and put information in 4th table <br/>and so on ....................<br/>}<br/><br/>go back to second item of list and try to put information in 1st table and use its id for other tables....<br/><br/>}</p> <p> Please let me know what exactly needs to be done here ?<br/>Thanks<br/>Varun</p> <p> </p> <p> </p> <p> </p> <p> </p> <p> </p> <p> </p> <p> </p> <p> </p> <p> </p> <p> </p> <p> </p> <p> </p> <p> </p> <p> </p> </span>Thu, 29 Oct 2009 19:52:01 Z2009-11-10T00:55:17Zhttp://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/546a8e60-277d-4623-9fcb-2234003e5305http://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/546a8e60-277d-4623-9fcb-2234003e5305jkastrinoshttp://social.msdn.microsoft.com/Profile/en-US/?user=jkastrinosIs this the correct forum for this HPC question?I am trying to run some of the Microsoft HPC examples and my jobs sit in the Configuring state.  I have completed the To-Do list and have a 3 node configuration using the Network Topology Selection # 5 - All nodes only on an Enterprise network.  I have successfully run the following Microsoft examples using my credentials which are a member of the Administrators group on all nodes:<br/><br/>Connecting to a Cluster (<a href="http://msdn.microsoft.com/en-us/library/cc853425(VS.85).aspx">http://msdn.microsoft.com/en-us/library/cc853425(VS.85).aspx</a>)<br/>Using Active Directory to Find the Head Nodes (<a href="http://msdn.microsoft.com/en-us/library/cc907077(VS.85).aspx">http://msdn.microsoft.com/en-us/library/cc907077(VS.85).aspx</a>)<br/>Getting a List of Nodes in the Cluster (<a href="http://msdn.microsoft.com/en-us/library/cc853436(VS.85).aspx">http://msdn.microsoft.com/en-us/library/cc853436(VS.85).aspx</a>)<br/>Getting a List of Jobs (<a href="http://msdn.microsoft.com/en-us/library/cc853435(VS.85).aspx">http://msdn.microsoft.com/en-us/library/cc853435(VS.85).aspx</a>)<br/><br/>When attempting the next example: Creating and Submitting a Job (<a href="http://msdn.microsoft.com/en-us/library/cc853426(VS.85).aspx">http://msdn.microsoft.com/en-us/library/cc853426(VS.85).aspx</a>), the jobs list in the Job Management queue with the Configuring state and do not proceed.  I have to cancel them.  I substituted the:<br/><br/><span style="font-family:Courier New">task.CommandLine = &quot;&lt;COMMANDGOESHERE&gt;&quot;;<br/></span><br/>with the name of an exe that resides on all nodes in the cluster that just sets the value of an integer and exits. When stepping through debug, after the following call:<br/><br/><span style="font-family:Courier New">scheduler.SubmitJob(job, @&quot;&lt;domain\username&gt;&quot;, null);<br/></span><br/>(modified to use my domain/id), the WaitOne blocking call never returns.  Any help is greatly appreciated.<br/>Thanks,<br/>jkastrinos<br/>Mon, 02 Nov 2009 17:41:54 Z2009-11-02T17:50:24Zhttp://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/8848449a-b333-480a-a5bf-ca1b4b971b6fhttp://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/8848449a-b333-480a-a5bf-ca1b4b971b6fVitaly Dilmukhametovhttp://social.msdn.microsoft.com/Profile/en-US/?user=Vitaly%20DilmukhametovWhen BlockingCollection<T>.TakeFromAny() return -1?Hi2all!<br/> <br/> I have one question: when BlockingCollection&lt;(Of &lt;T&gt;)&gt;.TakeFromAny() static method return -1?<br/> <br/> I read <a href="http://msdn.microsoft.com/en-us/library/dd267247(VS.100).aspx">MSDN Docs</a> that TakeFromAny() returns:<br/> <em><span><span><span>The index of the collection in the <span style="text-decoration:underline"><span class=parameter>collections</span> </span> array from which the item was removed, or -1 if an item could not be removed.</span> </span> </span> </em> <br/> <br/> Ok, but when item couldn't be removed? When <em>collections</em> parameter array contains empty not completed BlockingCollection&lt;T&gt; instances, the thread, called TakeFromAny() is blocked. <br/> <br/> Let me to show you an example. I have console application:<br/> <pre lang="x-c#">using System; using System.Collections.Generic; //using System.Linq; using System.Text; using System.Collections.Concurrent; using System.Threading; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { BlockingCollection&lt;int&gt; col1 = new BlockingCollection&lt;int&gt;(); BlockingCollection&lt;int&gt; col2 = new BlockingCollection&lt;int&gt;(); //Timer t1 = new Timer(delegate // { // // col1.Add(111); // col1.CompleteAdding(); // }, null, 1000, Timeout.Infinite); //Timer t2 = new Timer(delegate // { // //col2.Add(222); // //Thread.SpinWait(30000000); // col2.CompleteAdding(); // }, null, 2000, Timeout.Infinite); Console.WriteLine(DateTime.Now.ToLongTimeString()); int value; int indexOfCollection = BlockingCollection&lt;int&gt;.TakeFromAny(new[] { col1, col2 }, out value); Console.WriteLine(DateTime.Now.ToLongTimeString() + &quot; &quot; + value + &quot; index = &quot;+indexOfCollection); Console.WriteLine(&quot;Done&quot;); Console.ReadLine(); } } }</pre> <br/> In this case main app thread is blocked forever. If I uncomment lines with 2 timers creation, I have <em><span style="text-decoration:underline">ArgumentException</span> : At least one of the specified collections is marked as complete with regards to additions.<br/> Parameter name: collections</em> <br/> If I uncomment additional lines, where call Add method to both collections - it's ok, I take 111 value from col1.<br/> <br/> <strong>So I can't imagine situation, where TryTakeFrom() returns -1. Can you explain me, when it's possible?</strong> <br/> <br/> Thanks in advance!<br/> <br/> P.S. My Env: windows 2008 R2 RC, VS 2010 beta 2.Tue, 20 Oct 2009 16:03:20 Z2009-10-29T19:02:25Zhttp://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/a3d36832-c81e-4e51-b594-fdbc9d7c0e31http://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/a3d36832-c81e-4e51-b594-fdbc9d7c0e31John C MCSDhttp://social.msdn.microsoft.com/Profile/en-US/?user=John%20C%20MCSDDid Future<T> get dropped from .Net Framework 4.0?I'm curious, did Future&lt;T&gt; get dropped from .Net Framework 4.0?  If so, why?  And what do we use in its place?Thu, 29 Oct 2009 16:44:09 Z2009-11-01T02:32:22Zhttp://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/1397cf21-b51c-495a-be7f-d9984a54d1fdhttp://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/1397cf21-b51c-495a-be7f-d9984a54d1fdAMIMARhttp://social.msdn.microsoft.com/Profile/en-US/?user=AMIMARError - The name ‘Parallel’ does not exist in the current context - Parallel.For, VS2010, beta 2 I installed VS2010 beta 2 ultimate.<br/><br/>I tried to use Paralel.For with c# but I got the message:<br/>&quot;The name ‘Parallel’ does not exist in the current context&quot;<br/><br/>I set the properties of my project and to compile for the .Net 4.0 Framework.<br/>What else I can do resolve the problem?<br/><br/>Thanks in advance<br/><br/>Ami<br/>Tue, 27 Oct 2009 12:35:18 Z2009-10-29T17:16:20Zhttp://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/fe2b38ec-c4a3-47b6-a1b9-bdaf2d704268http://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/fe2b38ec-c4a3-47b6-a1b9-bdaf2d704268ykwokhttp://social.msdn.microsoft.com/Profile/en-US/?user=ykwokScability QuestionI am using a two Quad-core (8 cores in total) system and my program gives:<br/> <br/>         1         2          4         6       8<br/>         31.25   16.77   8.44    8.38    4.24<br/> <br/> I wonder why there is no improvement from CPU=4 to CPU=6.  Thank you.<br/> <br/> <br/> The program is:<br/> <br/> namespace Benchmark<br/> {<br/>     using System;<br/>     using System.Threading;<br/>     using System.Threading.Tasks;<br/> <br/>     public class Benchmark<br/>     {<br/>         private static double[] xgk = new double[17];<br/>         private static double[] wgk = new double[17];<br/>         private static double[] wg = new double[8];<br/> <br/>         public static double Eval(double x)<br/>         {<br/>             double sum = 0.0;<br/>             int i, j;<br/> <br/>             for (i = 3; i &lt; 100000; i++)<br/>             {<br/>                 for (j = 3; j &lt; 100; j++)<br/>                 {<br/>                     sum += Math.Pow(i + 0.01 * j, x);<br/>                 }<br/>             }<br/>             return sum;<br/>         }<br/> <br/> <br/>         public static double Run(int CPU)<br/>         {<br/>             int order = 15;<br/>             double half, a;<br/>             double res1, res2, res3, res4;<br/>             double[] fv1 = new double[17];<br/>             double[] fv2 = new double[17];<br/> <br/>             half = a = 0.5;<br/>             res1 = res2 = res3 = res4 = 0.0;<br/> <br/>             ParallelOptions options = new ParallelOptions();<br/>             options.MaxDegreeOfParallelism = CPU;<br/>             Object mutex = new Object();<br/> <br/>             long time = (DateTime.Now.Ticks - 621355968000000000) / 10000;<br/>             Parallel.For(0, order / 2, options,<br/>                 () =&gt;<br/>                 {<br/>                     return (new double[3]);<br/>                 }, (j, state, local) =&gt;<br/>                 {<br/>                     double b = half * xgk[2 * j + 1];<br/>                     double fval1 = Eval(a - b);<br/>                     double fval2 = Eval(a + b);<br/>                     fv1[2 * j + 1] = fval1;<br/>                     fv2[2 * j + 1] = fval2;<br/>                     double fsum = fval1 + fval2;<br/>                     // local[0] = res1, local[1] = res2, local[2] = res3<br/>                     local[0] += wg[j] * fsum;<br/>                     local[1] += wgk[2 * j + 1] * fsum;<br/>                     local[2] += wgk[2 * j + 1] * (System.Math.Abs(fval1) + System.Math.Abs(fval2));<br/>                     return local;<br/>                 },<br/>             local =&gt;<br/>             {<br/>                 lock (mutex)<br/>                 {<br/>                     res1 += local[0];<br/>                     res2 += local[1];<br/>                     res3 += local[2];<br/>                 }<br/>             });<br/> <br/>             Parallel.For(0, (order + 1) / 2, options,<br/>                 () =&gt;<br/>                 {<br/>                     return (new double[2]);<br/>                 }, (j, state, local) =&gt;<br/>                 {<br/>                     double b = half * xgk[2 * j];<br/>                     double fval1 = Eval(a - b);<br/>                     double fval2 = Eval(a + b);<br/>                     fv1[2 * j] = fval1;<br/>                     fv2[2 * j] = fval2;<br/>                     double fsum = fval1 + fval2;<br/>                     // local[0] = res2, local[1] = res4<br/>                     local[0] += wgk[2 * j] * fsum;<br/>                     local[1] += wgk[2 * j] * (System.Math.Abs(fval1) + System.Math.Abs(fval2));<br/>                     return local;<br/>                 },<br/>             local =&gt;<br/>             {<br/>                 lock (mutex)<br/>                 {<br/>                     res2 += local[0];<br/>                     res4 += local[1];<br/>                 }<br/>             });<br/>             time = (DateTime.Now.Ticks - 621355968000000000) / 10000 - time;<br/> <br/>             return ((double) time / 1000.0);<br/>         }<br/> <br/> <br/>         public static void Main(string[] args)<br/>         {<br/>             int[] cpu = { 1, 2, 4, 6, 8 };<br/>             double[] time = new double[cpu.Length];<br/>             int CPU;<br/>             Random rand = new Random();<br/> <br/>             // setup input.<br/>             for (int i = 0; i &lt; wgk.Length; i++)<br/>             {<br/>                 wgk[i] = rand.NextDouble();<br/>                 wgk[i] = rand.NextDouble();<br/>             }<br/> <br/>             for (int i = 0; i &lt; wg.Length; i++) wg[i] = rand.NextDouble();<br/> <br/>             // Run<br/>             for (int index = 0; index &lt; cpu.Length; index++)<br/>             {<br/>                 CPU = cpu[index];<br/>                 time[index] = Run(CPU);<br/>             }<br/> <br/>             Console.WriteLine(&quot;\t1\t2\t4\t6\t8&quot;);<br/>             for (int j = 0; j &lt; cpu.Length; j++) Console.Write(&quot;\t{0, 0:F2}&quot;, time[j]);<br/>             Console.WriteLine();<br/>         }<br/>     }<br/> }<br/>Wed, 28 Oct 2009 19:33:02 Z2009-10-30T09:58:52Zhttp://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/6481c589-ade1-409e-b40b-64fbe50c5e70http://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/6481c589-ade1-409e-b40b-64fbe50c5e70MarcZhouhttp://social.msdn.microsoft.com/Profile/en-US/?user=MarcZhouCancellation Framework in Beta 2 (CancellationTokenSource and Token)Hello,<br/><br/>I've a simple question about the new Cancellation Framework in .NET 4.0 Beta 2. I saw the example in the PFX Team Blog about using the new approach and I've some doubts about the using of the Token. Here is my example:<br/><br/> <pre lang="x-c#">public static void Example1() { CancellationTokenSource cts = new CancellationTokenSource(); Task myTask = Task.Factory.StartNew(() =&gt; { for (; ; ) { Console.WriteLine(&quot;Check for cancellation ...&quot;); <strong>cts.Token</strong>.ThrowIfCancellationRequested(); Console.WriteLine(&quot;wait&quot;); Thread.CurrentThread.Join(500); } }, <strong>cts.Token</strong>); Thread.CurrentThread.Join(2000); cts.Cancel(); }</pre> I need to understand the second parameter: Task.Factory.StartNew(..., CancellationToken). It is possible to use this value inside the created Task in the user code? I noticed that the value is assigned inside the Task class to an internal structure. Since the property Task.Current is removed, I've no reference to the Task instance itself. In the examle above I'm able to access the Token, because the CancellationTokenSource instance is declared as global variable. When I change the example to the version below, I've the same result (but I think it is not correct ...):<br/><br/> <pre lang="x-c#">public static void Example1() { CancellationTokenSource cts = new CancellationTokenSource(); Task myTask = Task.Factory.StartNew(() =&gt; { Task.Factory.StartNew(() =&gt; { for (; ; ) { Console.WriteLine(&quot;Check for cancellation ...&quot;); cts.Token.ThrowIfCancellationRequested(); Console.WriteLine(&quot;wait INNER&quot;); Thread.CurrentThread.Join(500); } }, cts.Token); for (; ; ) { Console.WriteLine(&quot;Check for cancellation ...&quot;); token.ThrowIfCancellationRequested(); Console.WriteLine(&quot;wait&quot;); Thread.CurrentThread.Join(500); } }); Thread.CurrentThread.Join(2000); cts.Cancel(); }</pre> In the example above I've removed the second parameter during the call to StartNew. I'm able to use the cts.Token inside the Task, because the the variable is available in this scope.<br/>What happens inside the Task with the Token? It is necessary to pass everytime the token to the Task object?<br/>Do you have a best practice or a pattern to use the Cancellation Framework correct?<hr class="sig">-Fri, 23 Oct 2009 08:42:52 Z2009-10-29T08:36:33Zhttp://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/7a3eaa3c-e361-4e8c-985f-1cc7fbeb978ahttp://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/7a3eaa3c-e361-4e8c-985f-1cc7fbeb978aPhil Winstanley ASP.NET MVPhttp://social.msdn.microsoft.com/Profile/en-US/?user=Phil%20Winstanley%20ASP.NET%20MVPParallel Managed Code - VS.NET 2010 Beta 2Hi All,<br/><br/>Just wondering what the status of the Parallel work in the Beta 2 release of VS.NET and .NET?<br/><br/>Is it all baked in now? What about changes/features?<br/><br/>Thanks,<br/><br/>Phil.Thu, 22 Oct 2009 10:34:21 Z2009-10-29T05:36:24Zhttp://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/05c761c2-e6b5-4338-86da-0c09f1c5e781http://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/05c761c2-e6b5-4338-86da-0c09f1c5e781Avivhttp://social.msdn.microsoft.com/Profile/en-US/?user=AvivLow CPU Utilization<p class="MsoNormal" style="margin: 0in 0in 0pt;"><span style="font-size: 10pt; color: navy; font-family: &quot;Verdana&quot;,&quot;sans-serif&quot;; mso-bidi-font-size: 11.0pt;">Hi,</span></p> <p class="MsoNormal" style="margin: 0in 0in 0pt;"><span style="font-size: 10pt; color: navy; font-family: &quot;Verdana&quot;,&quot;sans-serif&quot;; mso-bidi-font-size: 11.0pt;">I&rsquo;m running Daniel Moth&rsquo;s example of b-tree traversal from PDC 2008 (<a href="http://www.microsoft.com/emea/teched2008/developer/tv/default.aspx?vid=59#">http://www.microsoft.com/emea/teched2008/developer/tv/default.aspx?vid=59#</a>) using Tasks, on beta1 bits. </span></p> <p class="MsoNormal" style="margin: 0in 0in 0pt;"><span style="font-size: 10pt; color: navy; font-family: &quot;Verdana&quot;,&quot;sans-serif&quot;; mso-bidi-font-size: 11.0pt;">When I run it on an 8-core system (Win2008 Server) I see that I&rsquo;m only hitting max of 60-70% CPU utilization (all cores come into play). In dual-core I see around 80% utilization.</span></p> <p class="MsoNormal" style="margin: 0in 0in 0pt;"><span style="font-size: 10pt; color: navy; font-family: &quot;Verdana&quot;,&quot;sans-serif&quot;; mso-bidi-font-size: 11.0pt;">Is this expected? Shouldn&rsquo;t it be around 100% utilization?</span></p> <p class="MsoNormal" style="margin: 0in 0in 0pt;"><span style="font-size: 10pt; color: navy; font-family: &quot;Verdana&quot;,&quot;sans-serif&quot;; mso-bidi-font-size: 11.0pt;">&nbsp;</span></p> <p class="MsoNormal" style="margin: 0in 0in 0pt;"><span style="font-size: 10pt; color: navy; font-family: &quot;Verdana&quot;,&quot;sans-serif&quot;; mso-bidi-font-size: 11.0pt;">This is the actual code:</span></p> <p class="MsoNormal" style="margin: 0in 0in 0pt;"><span style="font-size: 10pt; color: navy; font-family: &quot;Verdana&quot;,&quot;sans-serif&quot;; mso-bidi-font-size: 11.0pt;">&nbsp;</span></p> <p class="MsoNormal" style="margin: 0in 0in 0pt; mso-layout-grid-align: none;"><span style="font-size: 9.5pt; color: blue; font-family: Consolas; mso-bidi-font-family: Consolas;">static</span><span style="font-size: 9.5pt; font-family: Consolas; mso-bidi-font-family: Consolas;"> <span style="color: blue;">void</span> TreeTraversal_TaskPerNode(<span style="color: #2b91af;">Tree</span> tree)</span></p> <p class="MsoNormal" style="margin: 0in 0in 0pt; mso-layout-grid-align: none;"><span style="font-size: 9.5pt; font-family: Consolas; mso-bidi-font-family: Consolas;">{</span></p> <p class="MsoNormal" style="margin: 0in 0in 0pt; mso-layout-grid-align: none;"><span style="font-size: 9.5pt; font-family: Consolas; mso-bidi-font-family: Consolas;"><span style="mso-spacerun: yes;">&nbsp;&nbsp;&nbsp; </span><span style="color: blue;">if</span> (tree == <span style="color: blue;">null</span>)</span></p> <p class="MsoNormal" style="margin: 0in 0in 0pt; mso-layout-grid-align: none;"><span style="font-size: 9.5pt; font-family: Consolas; mso-bidi-font-family: Consolas;"><span style="mso-spacerun: yes;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span><span style="color: blue;">return</span>;</span></p> <p class="MsoNormal" style="margin: 0in 0in 0pt; mso-layout-grid-align: none;"><span style="font-size: 9.5pt; font-family: Consolas; mso-bidi-font-family: Consolas;">&nbsp;</span></p> <p class="MsoNormal" style="margin: 0in 0in 0pt; mso-layout-grid-align: none;"><span style="font-size: 9.5pt; font-family: Consolas; mso-bidi-font-family: Consolas;"><span style="mso-spacerun: yes;">&nbsp;&nbsp;&nbsp; </span><span style="color: #2b91af;">Task</span> left = <span style="color: blue;">new</span> <span style="color: #2b91af;">Task</span>((o) =&gt; TreeTraversal_TaskPerNode(tree.Left), <span style="color: #2b91af;">TaskCreationOptions</span>.None);</span></p> <p class="MsoNormal" style="margin: 0in 0in 0pt; mso-layout-grid-align: none;"><span style="font-size: 9.5pt; font-family: Consolas; mso-bidi-font-family: Consolas;"><span style="mso-spacerun: yes;">&nbsp;&nbsp;&nbsp; </span>left.Start();</span></p> <p class="MsoNormal" style="margin: 0in 0in 0pt; mso-layout-grid-align: none;"><span style="font-size: 9.5pt; font-family: Consolas; mso-bidi-font-family: Consolas;"><span style="mso-spacerun: yes;">&nbsp;&nbsp;&nbsp; </span><span style="color: #2b91af;">Task</span> right = <span style="color: blue;">new</span> <span style="color: #2b91af;">Task</span>((o) =&gt; TreeTraversal_TaskPerNode(tree.Right), <span style="color: #2b91af;">TaskCreationOptions</span>.None);</span></p> <p class="MsoNormal" style="margin: 0in 0in 0pt; mso-layout-grid-align: none;"><span style="font-size: 9.5pt; font-family: Consolas; mso-bidi-font-family: Consolas;"><span style="mso-spacerun: yes;">&nbsp;&nbsp;&nbsp; </span>right.Start();</span></p> <p class="MsoNormal" style="margin: 0in 0in 0pt; mso-layout-grid-align: none;"><span style="font-size: 9.5pt; font-family: Consolas; mso-bidi-font-family: Consolas;">&nbsp;</span></p> <p class="MsoNormal" style="margin: 0in 0in 0pt; mso-layout-grid-align: none;"><span style="font-size: 9.5pt; font-family: Consolas; mso-bidi-font-family: Consolas;"><span style="mso-spacerun: yes;">&nbsp;&nbsp;&nbsp; </span>left.Wait();</span></p> <p class="MsoNormal" style="margin: 0in 0in 0pt; mso-layout-grid-align: none;"><span style="font-size: 9.5pt; font-family: Consolas; mso-bidi-font-family: Consolas;"><span style="mso-spacerun: yes;">&nbsp;&nbsp;&nbsp; </span>right.Wait();</span></p> <p class="MsoNormal" style="margin: 0in 0in 0pt; mso-layout-grid-align: none;"><span style="font-size: 9.5pt; font-family: Consolas; mso-bidi-font-family: Consolas;">&nbsp;</span></p> <p class="MsoNormal" style="margin: 0in 0in 0pt; mso-layout-grid-align: none;"><span style="font-size: 9.5pt; font-family: Consolas; mso-bidi-font-family: Consolas;"><span style="mso-spacerun: yes;">&nbsp;&nbsp;&nbsp; </span>ProcessItem(tree.Data);</span></p> <p class="MsoNormal" style="margin: 0in 0in 0pt;"><span style="font-size: 9.5pt; font-family: Consolas; mso-bidi-font-family: Consolas;">}</span><span style="font-size: 10pt; color: navy; font-family: &quot;Verdana&quot;,&quot;sans-serif&quot;; mso-bidi-font-size: 11.0pt;"></span></p> <p class="MsoNormal" style="margin: 0in 0in 0pt;"><span style="font-size: 10pt; color: navy; font-family: &quot;Verdana&quot;,&quot;sans-serif&quot;; mso-bidi-font-size: 11.0pt;">&nbsp;</span></p> <p class="MsoNormal" style="margin: 0in 0in 0pt;"><span style="font-size: 10pt; color: navy; font-family: &quot;Verdana&quot;,&quot;sans-serif&quot;; mso-bidi-font-size: 11.0pt;">Thanks,</span></p> <span style="font-size: 10pt; color: navy; font-family: &quot;Verdana&quot;,&quot;sans-serif&quot;; mso-fareast-font-family: 'Times New Roman'; mso-fareast-theme-font: minor-fareast; mso-bidi-font-family: 'Times New Roman'; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: HE; mso-no-proof: yes;">Aviv.</span>Tue, 06 Oct 2009 07:56:23 Z2009-10-22T07:10:26Zhttp://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/de6d9546-2c2b-4935-b302-c5dbe1db763bhttp://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/de6d9546-2c2b-4935-b302-c5dbe1db763bVitaly Dilmukhametovhttp://social.msdn.microsoft.com/Profile/en-US/?user=Vitaly%20DilmukhametovBasic Concurrent data structures questionHi2all!<br/> <br/> I have one conceptual question to Parallel Fx team. For example, I have 1 concurrent queue with 3 elements. And 2 threads try to dequeue 1 element simultaneously. <a href="http://msdn.microsoft.com/en-us/library/dd287208(VS.100).aspx">MSDN documentation</a> noticed:<br/> &quot;<strong>Return Value</strong> <span> Type: System<span class=cpp></span> <span class=nu>.</span> Boolean<br/> <span><span><em>true </em> if an element was removed and returned from the beggining of the <em><span>ConcurrentQueue<span class=cs>&lt;</span> <span class=vb>(Of </span> <span class=cpp>&lt;</span> <span class=nu>(</span> T<span class=cs>&gt;</span> <span class=vb>)</span> <span class=cpp>&gt;</span> <span class=nu>)</span> </span> </em> succesfully; otherwise, <em>false</em> .</span> </span> </span> &quot;<br/> Ok, and what about described situation? Both threads returns two first values from queue? Or 2nd thread returns false?<br/> <br/> Can you explain me, when exactly TryDequeue() method return false?<br/> <br/> Thank you!Mon, 19 Oct 2009 18:40:05 Z2009-10-22T02:34:10Zhttp://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/b8780b7f-c6c0-4ecf-a550-0e81ff030c2ahttp://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/b8780b7f-c6c0-4ecf-a550-0e81ff030c2aHemant Jangidhttp://social.msdn.microsoft.com/Profile/en-US/?user=Hemant%20JangidDifferent output of 2 seemingly same code snippetConsider following console application: <div><br /></div> <div> <pre lang="x-c#"> class Program { static void Main (string[] args) { string targetPath = @"D:\Test"; var files = Directory.GetFiles (targetPath); //Parallel method Parallel.ForEach (files, f =&gt; Console.WriteLine (f)); //Classic method foreach (string f in files) Task.Factory.StartNew (() =&gt; Console.WriteLine (f)); Console.ReadLine (); } }</pre> Assume that I have four files in "D:\Test" folder: "1.txt", "2.txt", "3.txt", "4.txt".</div> <div><br /></div> <div>When I run about program, first method i.e. Parallel method prints (correctly):</div> <div> <div>D:\Test\1.txt</div> <div>D:\Test\2.txt</div> <div>D:\Test\3.txt</div> <div>D:\Test\4.txt</div> <div><br /></div> </div> <div>But the classic method prints:</div> <div> <div>D:\Test\4.txt</div> <div>D:\Test\4.txt</div> <div>D:\Test\4.txt</div> <div>D:\Test\4.txt</div> <div><br /></div> <div>Why do classic way doesn't work whereas Parallel one does?</div> <div><br /></div> <div>P.S.: Please let me know if you need me to explain why do I need to use classic foreach.</div> </div>Wed, 14 Oct 2009 12:28:17 Z2009-10-15T04:43:52Zhttp://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/bd2ff972-59c3-4781-b77b-53249abf717bhttp://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/bd2ff972-59c3-4781-b77b-53249abf717bphilippe lombaershttp://social.msdn.microsoft.com/Profile/en-US/?user=philippe%20lombaersCreating many classes instances in parallelHello,<br /><br />My scenario is the following :<br />I have a server app that creates entitty collections and transforms those into DTO (data transport objects - WCF).<br />List&lt;CustomerDTO&gt; custDto = new List&lt;CustomerDTO&gt;<br />foreach (CustomerEntity cust in custEntities)<br />&nbsp; custDto.Add(cust.ToDto());<br />This consists of only creating an object (DTO) and filling its properties with the entity properties.<br />Can I expect some performace improvements on a multicore machine by using parallel extension ?<br />One important thing is that the order should remain the same since it is the result of an ORDER BY.<br /><br />Thanks<hr class="sig">philippeTue, 06 Oct 2009 07:21:36 Z2009-10-13T07:06:15Zhttp://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/38d604ae-af91-4218-bb4d-80ab65937867http://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/38d604ae-af91-4218-bb4d-80ab65937867Andy Clymerhttp://social.msdn.microsoft.com/Profile/en-US/?user=Andy%20ClymerSelf Replicating Task In the CTP there was an option to Create a Task with the option SelfReplicating, I can't seem to find that option in .NET 4.  Has this functionality been lost from the Task based API. <div><br/></div>Fri, 14 Aug 2009 05:48:28 Z2009-10-09T01:08:20Zhttp://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/308970b4-4e2b-411c-80e8-da0cf6f6ecf5http://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/308970b4-4e2b-411c-80e8-da0cf6f6ecf5Torsten Langnerhttp://social.msdn.microsoft.com/Profile/en-US/?user=Torsten%20LangnerParallel.For Slows Down with more coresHi,<br /><br />I'm running my test app on&nbsp;Intel Xeon 514 / 2.33 GHz, 2 Sockets, 2 Cores each, 4 GB RAM<br /><br />the test app is a Monte Carlo Scenario that creates 500.000 objects of Type Mandelbrot; each object creates random values and forecasts 20 days; the result is 500.000 x 20 random values<br /><br />the code looks like:<br /><br /><span style="color: #0000ff; font-size: xx-small;"><span style="color: #0000ff; font-size: xx-small;">for</span></span><span style="font-size: xx-small;"> (</span><span style="color: #0000ff; font-size: xx-small;"><span style="color: #0000ff; font-size: xx-small;">int</span></span><span style="font-size: xx-small;"> CurrentDayOfForecast = 0; CurrentDayOfForecast &lt; ForecastRange; CurrentDayOfForecast++)<br />{<br /></span><span style="color: #0000ff; font-size: xx-small;"><span style="color: #0000ff; font-size: xx-small;">&nbsp;&nbsp;&nbsp; #region</span></span><span style="font-size: xx-small;"> Calculate Current Day<br /></span><span style="color: #2b91af; font-size: xx-small;"><span style="color: #2b91af; font-size: xx-small;">&nbsp;&nbsp;&nbsp; Parallel</span></span><span style="font-size: xx-small;">.ForEach(Mandelbrot, </span><span style="color: #0000ff; font-size: xx-small;"><span style="color: #0000ff; font-size: xx-small;">delegate</span></span><span style="font-size: xx-small;">(</span><span style="color: #2b91af; font-size: xx-small;"><span style="color: #2b91af; font-size: xx-small;">_30DaysUpDown_II_Mandelbrot</span></span><span style="font-size: xx-small;"> CurrentMandelbrot)<br />&nbsp;&nbsp;&nbsp; {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; CurrentMandelbrot.Forecast(CurrentDayOfForecast);<br />&nbsp;&nbsp;&nbsp; });<br /></span><span style="color: #0000ff; font-size: xx-small;"><span style="color: #0000ff; font-size: xx-small;">&nbsp;&nbsp;&nbsp; #endregion</span></span><span style="font-size: xx-small;"><br />} <p>when I&nbsp;run this code on 1 Socket (2 cores) the&nbsp;server is utilized at 45-48% and the code finishes after 40 seconds<br />when I run this code on 2 Sockes (4 cores) the server is utilized at 96-98% and the code finishes after 55 seconds<br /><br />so more cores = slow down<br /><br /><br />Any hints?</p> </span>Fri, 02 Oct 2009 12:19:34 Z2009-10-05T13:49:16Zhttp://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/c8ac3895-cf61-4b29-839c-66ef1af7ad38http://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/c8ac3895-cf61-4b29-839c-66ef1af7ad38K_Mhttp://social.msdn.microsoft.com/Profile/en-US/?user=K_MDetermining current Task ID from within an addin or debugger visualizer<p>Suppose I halt at a breakpoint when debugging an application.  From within an addin or debugger visualizer I can access the debugger object, and from that determine the thread that was executing when the breakpoint was hit.  But I can't see any way of determining the task (or even the ID of the task) that was executing at that point.  I can get this information via the Parallel Tasks panel, by finding the row with the yellow arrow, so the information is clearly available at some level.  But I'd like to access this information programmatically, so is there a method that can be called to return the ID of the task currently running on a given thread that can be called when an application is &quot;suspended&quot; at a breakpoint?</p>Wed, 30 Sep 2009 10:56:53 Z2009-10-02T09:16:26Zhttp://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/7628559d-39f4-4183-a898-0975b69b39bfhttp://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/7628559d-39f4-4183-a898-0975b69b39bfykwokhttp://social.msdn.microsoft.com/Profile/en-US/?user=ykwokBarrier questionI got the following output for a run of the example below.  The way I used the Barrier must be wrong because I expect the cpu (# of threads created) to be the same, e.g. cpu = 5 for every line.  What is the correct way to use it?  Thank you.<br/> <br/> cpu = 4, i = 1<br/> cpu = 4, i = 2<br/> cpu = 4, i = 3<br/> cpu = 4, i = 0<br/> cpu = 5, i = 0<br/> cpu = 5, i = 4<br/> cpu = 5, i = 2<br/> cpu = 5, i = 1<br/> cpu = 5, i = 3<br/> cpu = 5, i = 3<br/> cpu = 5, i = 0<br/> cpu = 5, i = 4<br/> cpu = 5, i = 1<br/> cpu = 5, i = 2<br/> cpu = 5, i = 0<br/> cpu = 5, i = 0<br/> <br/> ============================ code example ====================<br/> <br/> public static void Main(string[] args)<br/>         {<br/>             int cpu = 0;<br/>             double[,] mutex = new double[1, 1];<br/>             Barrier barrier = new Barrier(0);<br/>             System.Threading.Tasks.Parallel.For(0, 16, () =&gt;<br/>             {<br/>                 barrier.AddParticipant();<br/>                 lock (mutex)<br/>                 {<br/>                     int id = cpu;<br/>                     cpu++;<br/>                     return id;<br/>                 }<br/>                 <br/>             }, (i, state, local) =&gt;<br/>             {<br/>                 barrier.SignalAndWait();<br/>                 Console.WriteLine(&quot;cpu = &quot; + cpu + &quot;, i = &quot; + local);<br/>                 for (int j = 0; j &lt; 20000000; j++) { }<br/>                 return local;<br/>             },<br/>             local =&gt;<br/>             {<br/>                 barrier.RemoveParticipant();<br/>             });<br/>         }Mon, 28 Sep 2009 20:01:37 Z2009-10-05T01:05:50Zhttp://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/0790b69b-acbd-4b4c-bbd9-7d1c4da1a4efhttp://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/0790b69b-acbd-4b4c-bbd9-7d1c4da1a4efThomas _LA_http://social.msdn.microsoft.com/Profile/en-US/?user=Thomas%20_LA_Iterating over a DataColumnCollectionIn a recent project, I discovered the hard way that iterating over a columns collection, even read-only is not thread-safe. I.e. something like:<br/> <br/> Parallel.Foreach(..<br/>    foreach(DataColumn foo in mytable.Columns)<br/>    ...<br/> <br/> My question is whether using indexes in a standard For loop is thread-safe. I.e. instead of the above, something like:<br/> <br/> Parallel.Foreach(..<br/>    for(var i = 0; i &lt; mytable.Columns.Count; i++)<br/>    ...<br/> <br/> It should be noted that I'm using the June CTP of the Parallel Extentions for .NET 3.5.Thu, 24 Sep 2009 20:26:27 Z2009-09-29T01:13:02Zhttp://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/11fba35a-afcd-4175-b374-4ecdac9c6ffehttp://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/11fba35a-afcd-4175-b374-4ecdac9c6ffeykwokhttp://social.msdn.microsoft.com/Profile/en-US/?user=ykwokloop incrementHow to convert a for with a increment to Parallel.For?<br/> <br/> for (int i = 0; i &lt; n; i += block)<br/> {<br/> ...<br/> }Mon, 28 Sep 2009 20:19:29 Z2009-10-01T16:47:51Zhttp://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/268414a9-8fe8-4120-98b2-2e00dece67bchttp://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/268414a9-8fe8-4120-98b2-2e00dece67bcThomas _LA_http://social.msdn.microsoft.com/Profile/en-US/?user=Thomas%20_LA_Break out of Parallel.Foreach in June CTPHow do you break out of a Parallel.Foreach loop in the June CTP? I see that in the .NET 4.0 extensions they have added the ability to do so, but how do you do it in the previous set of extensions?Thu, 24 Sep 2009 20:27:40 Z2009-09-26T00:33:48Zhttp://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/ae26c8b7-ce88-4c87-b17e-8e22f5eb3cb2http://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/ae26c8b7-ce88-4c87-b17e-8e22f5eb3cb2K_Mhttp://social.msdn.microsoft.com/Profile/en-US/?user=K_MHow does the Parallel Tasks debugging window get access to the list of current tasks?<span><span> <p>I'm writing a Visual Studio debugging visualizer and I'd like to be able to access the state of all the current tasks in the process being debugged when it is halted at a breakpoint. The Parallel Tasks debugging window illustrates that there must be some way of doing this, but I've not found anything in the various threading APIs that gives me access to this infomation. The closest thing I found was the GetScheduledTasks</p> </span><span lang=EN-GB> method in the TaskScheduler class. But using reflection to call this (as it's protected) on the default scheduler only produced a subset of the tasks shown in the tasks debugging window. And I couldn't see anything else that would enumerate all the current task schedulers, so I'm presumably going down a dead end. So does anyone know how the Parallel Tasks debugging window gets hold of the list of current tasks?</span></span>Thu, 24 Sep 2009 15:31:22 Z2009-09-25T08:22:42Zhttp://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/f4f54c48-a052-4c4c-af23-eb793374e05chttp://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/f4f54c48-a052-4c4c-af23-eb793374e05cMarcZhouhttp://social.msdn.microsoft.com/Profile/en-US/?user=MarcZhouCancel Tasks within Parallel.InvokeI've checked out the code from the Parallel.Invoke method, especially the method with the ParallelOptions parameter. I noticed that the method throws an exception when the CancellationToken is set to CANCELED (IsCancellationRequested=true -&gt; OperationCanceledException). That is good! But how can I cancel the created task objects? It is possible? At the moment I've no access to the created task objects and the CancellationToken is not transfered to the task objects.<hr class="sig">-Sat, 19 Sep 2009 18:08:50 Z2009-09-22T04:42:49Zhttp://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/4c75bf95-e789-4ff4-b883-7f69d5e27347http://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/4c75bf95-e789-4ff4-b883-7f69d5e27347DanielHOferhttp://social.msdn.microsoft.com/Profile/en-US/?user=DanielHOferVB Parallel.For sample to calc Primes with run times for Intel Core i7 Processor<pre>VB Parallel.For Test Application calculating Primes with ParallelExtensions to .NET 3.5 These are run times from the code that follows: Non-Parallel Time: H:M:S 0: 0: 0.2 #Primes: 78,498 [7.85%] for Range: 1 - 1,000,000 Parallel Time: H:M:S 0: 0: 0.2 #Primes: 78,498 [7.85%] for Range: 1 - 1,000,000 SieveOfErathothenes Time: H:M:S 0: 0: 0 #Primes: 78,498 [7.85%] for Range: 1 - 1,000,000 SieveOfErathoParallel Time: H:M:S 0: 0: 0.3 #Primes: 78,498 [7.85%] for Range: 1 - 1,000,000 Non-Parallel Time: H:M:S 0: 2: 10.8 #Primes: 5,761,455 [5.76%] for Range: 1 - 100,000,000 Parallel Time: H:M:S 0: 0: 22.8 #Primes: 5,761,455 [5.76%] for Range: 1 - 100,000,000 SieveOfErathothenes Time: H:M:S 0: 0: 1.7 #Primes: 5,761,455 [5.76%] for Range: 1 - 100,000,000 SieveOfErathoParallel Time: H:M:S 0: 0: 19.6 #Primes: 5,761,455 [5.76%] for Range: 1 - 100,000,000 Non-Parallel Time: H:M:S 1: 7: 54.1 #Primes: 50,847,534 [5.08%] for Range: 1 - 1,000,000,000 Parallel Time: H:M:S 0: 11: 6.7 #Primes: 50,847,534 [5.08%] for Range: 1 - 1,000,000,000 SieveOfErathothenes Time: H:M:S 0: 0: 20 #Primes: 50,847,534 [5.08%] for Range: 1 - 1,000,000,000 SieveOfErathoParallel Time: H:M:S 0: 5: 30.7 #Primes: 50,847,534 [5.08%] for Range: 1 - 1,000,000,000 Note: Add Reference to Project, Browse Tab: C:\Program Files (x86)\Microsoft Parallel Extensions Jun08 CTP\System.Threading Imports System.Threading.Tasks Imports System.Threading Public Class Form1 Dim primeCounter As Integer 'Form objects to add: ' Button: btnCalcPrimes, btnSieveOfEratosthenes ' Textboxes: txtStartInteger, txtEndInteger, txtPrimes [multi-line, font:Courier New, 8.25pt, size 840x440], txtCounter ' Checkbox: chkCalcParallel, chkListPrimes, chkShowMiscount, chkClearText Private Sub btnCalcPrimes_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalcPrimes.Click Dim i, j, miscount As Integer Dim pcMiscount, pcPrimes As Single Dim firstInteger As Integer = CInt(txtStartInteger.Text) Dim lastInteger As Integer = CInt(txtEndInteger.Text) Dim results(lastInteger) As Boolean Dim s As String = &quot;&quot; Dim duration As String = &quot;start&quot; getDuration(duration) primeCounter = 0 If chkClearText.Checked Then txtPrimes.Text = &quot;&quot; txtPrimes.Refresh() If firstInteger Mod 2 = 0 Then firstInteger += 1 'do odds only If chkCalcParallel.Checked Then Parallel.For(firstInteger, lastInteger, 2, Function(index As Integer) Prime(index, results)) duration = &quot;&quot; getDuration(duration) j = 0 For i = 1 To lastInteger If results(i) Then j += 1 Next Debug.Print(primeCounter.ToString) miscount = j - primeCounter pcMiscount = Math.Round(100 * (miscount / j), 2) primeCounter = j Else For i = firstInteger To lastInteger Step 2 Prime(i, results) If primeCounter Mod 100000 = 0 Then txtCounter.Text = primeCounter.ToString txtCounter.Refresh() End If Next duration = &quot;&quot; getDuration(duration) End If txtCounter.Text = primeCounter txtCounter.Refresh() pcPrimes = Math.Round(100 * (primeCounter / (CInt(txtEndInteger.Text) - CInt(txtStartInteger.Text) + 1)), 2) s = IIf(chkCalcParallel.Checked, &quot; &quot;, &quot; Non-&quot;) + &quot;Parallel Time: &quot; + duration + &quot; #Primes: &quot; + prnr(primeCounter.ToString, 8) _ + &quot; [&quot; + pcPrimes.ToString + &quot;%] for Range: &quot; + txtStartInteger.Text + &quot; - &quot; + txtEndInteger.Text _ + IIf(chkCalcParallel.Checked And chkShowMiscount.Checked, &quot; miscount: &quot; + miscount.ToString _ + &quot; [&quot; + pcMiscount.ToString + &quot;%]&quot;, &quot;&quot;) + vbCrLf If chkListPrimes.Checked Then s += getPrimeList(results) txtPrimes.Text = s End Sub Function Prime(ByVal index As Integer, ByVal results As Boolean()) Dim i, j As Integer j = Math.Sqrt(index) results(index) = False If index = 1 Then '2 is the first prime Prime = Nothing results(index + 1) = True primeCounter += 1 Exit Function End If If j &lt; 3 Then Prime = Nothing results(index) = True primeCounter += 1 Exit Function End If For i = 3 To j Step 2 'checking odds only in Prime If index Mod i = 0 Then Prime = Nothing results(index) = False Exit Function End If Next Prime = Nothing results(index) = True primeCounter += 1 End Function Public Function prnl(ByVal s As String, ByVal i As Integer) As String If s = &quot;&quot; Then s = &quot; &quot; If i = 0 Then i = 1 End If If s.Length &gt; i Then s = Mid(s, 1, i - 1) + &quot;?&quot; prnl = Trim(s) + Space(i - Len(Trim(s))) End Function Public Function prnr(ByVal s As String, ByVal i As Integer) As String If s = &quot;&quot; Then s = &quot; &quot; If i = 0 Then i = 1 End If If s.Length &gt; i Then s = Mid(s, 1, i - 1) + &quot;?&quot; prnr = Space(i - Len(Trim(s))) + Trim(s) End Function Private Sub getDuration(ByRef s As String) Dim hrs, mins As Integer Dim secs As Single Static dtstart As DateTime Dim dtnow As DateTime Dim ts As TimeSpan If s.ToLower = &quot;start&quot; Then dtstart = DateTime.Now s = dtstart Else dtnow = DateTime.Now ts = dtnow.Subtract(dtstart).Duration hrs = Int(ts.TotalHours) mins = Int(ts.TotalMinutes) - hrs * 60 secs = Math.Round((ts.TotalSeconds) - mins * 60 - hrs * 3600, 1) s = &quot;H:M:S &quot; + prnr(hrs.ToString, 3) + &quot;:&quot; + prnr(mins.ToString, 3) + &quot;:&quot; + prnr(secs.ToString, 5) End If End Sub Private Sub txtStartInteger_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtStartInteger.Leave txtStartInteger.Text = Format(CInt(txtStartInteger.Text), &quot;###,###,###,###,###&quot;) End Sub Private Sub txtEndInteger_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtEndInteger.Leave txtEndInteger.Text = Format(CInt(txtEndInteger.Text), &quot;###,###,###,###,###&quot;) End Sub Private Sub txtCounter_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtCounter.TextChanged If txtCounter.Text &lt;&gt; &quot; &quot; Then txtCounter.Text = Format(CInt(txtCounter.Text), &quot;###,###,###,###,###&quot;) End If End Sub Private Sub btnSieveOfErathsthenes_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSieveOfErathsthenes.Click Dim i, j, sqrlastInteger As Integer Dim firstInteger As Integer = CInt(txtStartInteger.Text) Dim lastInteger As Integer = CInt(txtEndInteger.Text) Dim pcPrimes As Single Dim s As String Dim duration As String = &quot;start&quot; getDuration(duration) If chkClearText.Checked Then txtPrimes.Text = &quot;&quot; sqrlastInteger = CInt(Math.Sqrt(lastInteger)) Dim A(lastInteger) As Boolean For i = Math.Max(firstInteger, 2) To lastInteger A(i) = True Next 'set every multiple of 2 through sqrlastInteger to false, the rest are Primes ' eliminate odd composite numbers If chkCalcParallel.Checked Then For i = 3 To sqrlastInteger Step 2 Parallel.For(2 * i, lastInteger, i, Function(index As Integer) Prime(index, A)) Next Else For i = 3 To sqrlastInteger Step 2 If A(i) Then For j = 2 * i To lastInteger Step i A(j) = False Next End If Next End If ' eliminate all evens For i = 4 To lastInteger Step 2 A(i) = False Next duration = &quot;&quot; getDuration(duration) j = 0 For i = firstInteger To lastInteger If A(i) Then j += 1 Next primeCounter = j txtCounter.Text = primeCounter txtCounter.Refresh() pcPrimes = Math.Round(100 * (primeCounter / (CInt(txtEndInteger.Text) - CInt(txtStartInteger.Text) + 1)), 2) s = IIf(chkCalcParallel.Checked, &quot;SieveOfErathoParallel&quot;, &quot; SieveOfErathothenes&quot;) + &quot; Time: &quot; + duration + &quot; #Primes: &quot; _ + prnr(primeCounter.ToString, 8) + &quot; [&quot; + pcPrimes.ToString + &quot;%] for Range: &quot; + txtStartInteger.Text + &quot; - &quot; + txtEndInteger.Text + vbCrLf If chkListPrimes.Checked Then s += getPrimeList(A) txtPrimes.Text += s End Sub Function EliminateNonPrimes(ByVal index As Integer, ByVal results As Boolean()) results(index) = False Return False End Function Function getPrimeList(ByVal A As Boolean()) As String Dim i, j As Integer Dim s As String = &quot;&quot; j = 0 For i = 1 To A.GetUpperBound(0) If A(i) Then j += 1 If j Mod 10 = 0 Then 'end of row prime # counter s += prnr(i.ToString, 10) s += prnr(j.ToString, 10) + vbCrLf Else s += prnr(i.ToString, 10) End If End If Next If j Mod 10 &lt;&gt; 0 Then Dim k As Integer = (11 - (j Mod 10)) * 10 s += prnr(j.ToString, k) + vbCrLf End If getPrimeList = s End Function End Class</pre><hr class="sig">DanielHOferMon, 21 Sep 2009 21:06:28 Z2009-09-21T21:06:28Zhttp://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/bb32f0f8-cffb-4075-9a44-a9dccf501720http://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/bb32f0f8-cffb-4075-9a44-a9dccf501720DanielHOferhttp://social.msdn.microsoft.com/Profile/en-US/?user=DanielHOferParallel work on 3D Data Structure?<p>VB 2008 &amp; .net 3.5 Parallel Extensions, Vista Ultimate, 12GB memory, Intel Core(TM) i7 CPU. (4 cores). Affinity as set to all 8 &quot;cpu's&quot;.:</p> <p>I'm reading 15 criscrossing vertical 2D planes of geologic data from a 1-D data structure, Vels(i).V and averaging values within a given horizontal radius to a uniform spaced 3d bin volume array, Vsmooth(j, k, layer). I process 1 layer in each call to Coresow, so no data element in the input structure or output array is used in more than 1 layer. The current layer is determined inside Coresow. There is also a data structure I use to lookup the relationship between i's and the j, k bin location.</p> <p><br/>My non-parallel time through 101 layers took ~46 minutes.</p> <p> For i = 1 To Layers <br/>   CoreSow()<br/> Next</p> <p><br/>My Parallel.For trial took ~26 hours, parallel automatically set up 20 threads at a time, only 1 core was used though, at ~13% cpu. <br/> <br/> Parallel.For(1, Layers, AddressOf CoreSow)</p> <p><br/>My Tasks trial took ~17 hours, I wanted to use only 4 cores at a time, and they were, but the total CPU Usage was still ~15%.</p> <p> For i = 1 To Layers Step 4<br/>  k = -1<br/>  For j = i To i + 3 '4 layers at a time<br/>   k += 1 'in cores 0 to 3<br/>   t(k) = Tasks.Task.Create(AddressOf CoreSow)<br/> Next j<br/>  Task.WaitAll(t(0), t(1), t(2), t(3))<br/> Next i</p> <p>The results were corrrect from all 3 runs.</p> <p>Is there a problem in referencing the same input and output data structures/arrays even though no common elements are used in more than 1 call to Coresow?</p> <p>Is there a good source of VB example code?</p> <p>Thanks for your help.</p><hr class="sig">DanielHOferThu, 10 Sep 2009 15:04:11 Z2009-09-21T21:02:13Zhttp://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/bd44e065-4402-49b0-aae1-1f9bec808478http://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/bd44e065-4402-49b0-aae1-1f9bec808478MatthieuMEZIL-MVPhttp://social.msdn.microsoft.com/Profile/en-US/?user=MatthieuMEZIL-MVPContinueWith issueHi<br/>Can anybody explains me why the following code don't write anything in the Console. Thanks<br/>Matthieu<br/> <pre lang="x-c#">static void Main(string[] args) { Task t = null; t = new Task(() =&gt; { for (int i = 0; i &lt; 10; i++) t.ContinueWith(t2 =&gt; Console.WriteLine(i)); }); t.Start(); t.Wait(); } </pre>Tue, 15 Sep 2009 21:10:42 Z2009-09-16T17:53:30Zhttp://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/b1c4dfe8-e07b-40e9-8c3d-9bae89b07499http://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/b1c4dfe8-e07b-40e9-8c3d-9bae89b07499jayddhttp://social.msdn.microsoft.com/Profile/en-US/?user=jayddQuestions about PLINQHi,<br/> <br/> I have a couple of questions about PLINQ - one general and one specific - <br/> <br/> (1) -&gt; I have been using LINQ (and now PLINQ) extensively and in particular like the functional abstraction it gives you in terms of just saying what tasks you want parallelized (not how) and it is done for you - and then I see all these posts about Imperative function calls like Tasks.Create, Tasks.Wait(), Parallel.ForAll() etc - so my question is - am I missing out on really cool API functions under the hood in TPL, when I have been just going gaga over PLINQ - in other words what are the class of problems for which I must leave PLINQ because its ineffective and then code imperatively using such calls - i understand these are broad questions - but necessary to wrap my mind around these new technologies...<br/> <br/> (2) -&gt; Specifically, I have some PLINQ code where I am reading sequentially from a System.Data.DataReader and creating a lazy list using yield return - whose consumption I will then attempt to parallelize after calling .AsParallel() on the list - my question is have I really parallelized the consumption of the list or its production? - would multiple tasks be working to get me as many records from the database - or is it one task getting all the records and many tasks then consuming it?<br/> <br/> <br/> Thanks in advance...<br/><hr class="sig">jayddThu, 10 Sep 2009 18:35:29 Z2009-09-13T17:08:46Z