Solved

multithreading in a loop C#

Posted on 2013-12-16
8
347 Views
Last Modified: 2014-01-08
Hi;

I have a loop that has a function call in it which operates on some calculation and returns a string array.

The function accepts incoming values. The things that I expect to do in that function is serializable and thread safe.

So, how can i achieve this in multithreaded idea?

Should i create a seperate class for this or what to do?

Pseudocode:
public string[] GetAAA(string a, MyClass myObject)
{
...
 for (int i = 0; i < someLength; i++)
                {
arrRes[i] = obj.foo(a, b, c, d) ; // a, b, c, d are serializable
...
}

}

Open in new window

0
Comment
Question by:jazzIIIlove
  • 4
  • 4
8 Comments
 
LVL 29

Expert Comment

by:Göran Andersson
ID: 39721452
The simplest would be to use PLINQ to run the methods using several threads. Example:

addRes = Enumerable.Range(0, someLength)
  .AsParallel()
  .AsOrdered()
  .Select(i => obj.foo(a, b, c, d))
  .ToArray();

Open in new window


(Requires framework 4.0 or later.)
0
 
LVL 12

Author Comment

by:jazzIIIlove
ID: 39721745
Hi;

I was just considering it. Great and clever!

One dummy question, is your code segment replaces that for loop completely in that function?

I mean, your code:

addRes = Enumerable.Range(0, someLength)
  .AsParallel()
  .AsOrdered()
  .Select(i => obj.foo(a, b, c, d))
  .ToArray();

Open in new window


Is more detailed one like this?
public string[] GetAAA(string a, MyClass myObject)
{
...//no for loop
addRes = Enumerable.Range(0, someLength)
  .AsParallel()
  .AsOrdered()
  .Select(i => obj.foo(a, b, c, d))
  .ToArray();
...
}

Open in new window

0
 
LVL 29

Expert Comment

by:Göran Andersson
ID: 39722943
Yes, that is right.

Using AsParallel will make it run in several threads, and using AsOrdered will make sure that the items in the result is in the order of the initial range.
0
Comprehensive Backup Solutions for Microsoft

Acronis protects the complete Microsoft technology stack: Windows Server, Windows PC, laptop and Surface data; Microsoft business applications; Microsoft Hyper-V; Azure VMs; Microsoft Windows Server 2016; Microsoft Exchange 2016 and SQL Server 2016.

 
LVL 12

Author Comment

by:jazzIIIlove
ID: 39727287
Hi,

I have seen Parallel.For(
in some examples. Can i use this instead? Note that order of execution is still important.

Regards.
0
 
LVL 29

Expert Comment

by:Göran Andersson
ID: 39728252
You could, but Parallel.For doesn't return a collection of results, so you would have to collect the results yourself, and rearrange them into the right order. As you are doing that from several threads, you also need to synchronise the access between them. PLINQ does all that for you.
0
 
LVL 12

Author Comment

by:jazzIIIlove
ID: 39728967
ok, i understand but i was using the array element,
arrRes[i] 

Open in new window

in the code and the index. So, i guess Parallel. For is more relevant but how can i rearrange them? Do i need a old-school lock mechanism for this?

Regards.
0
 
LVL 12

Author Comment

by:jazzIIIlove
ID: 39729011
What I have done is that:
System.Collections.Concurrent.ConcurrentStack<string> results = new System.Collections.Concurrent.ConcurrentStack<string>();

Parallel.For(0, someLength, i =>
{
someString = someArray[i];

arrRes[i] = someObject.someFunction(....);
results.Push(arrRes[i]);

Open in new window


My question is that with the current code, do i provide concurrency by using ConcurrentStack instance?

Regards.
0
 
LVL 29

Accepted Solution

by:
Göran Andersson earned 500 total points
ID: 39730212
That would work for collecting the results, but you would need to include the index in each result also, so that you can sort them afterwards. Now they would end up in the collection in the order that they would happen to be completed.
0

Featured Post

Are your AD admin tools letting you down?

Managing Active Directory can get complicated.  Often, the native tools for managing AD are just not up to the task.  The largest Active Directory installations in the world have relied on one tool to manage their day-to-day administration tasks: Hyena. Start your trial today.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In order to hide the "ugly" records selectors (triangles) in the rowheaders, here are some suggestions. Microsoft doesn't have a direct method/property to do it. You can only hide the rowheader column. First solution, the easy way The first sol…
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
In a recent question (https://www.experts-exchange.com/questions/28997919/Pagination-in-Adobe-Acrobat.html) here at Experts Exchange, a member asked how to add page numbers to a PDF file using Adobe Acrobat XI Pro. This short video Micro Tutorial sh…
Email security requires an ever evolving service that stays up to date with counter-evolving threats. The Email Laundry perform Research and Development to ensure their email security service evolves faster than cyber criminals. We apply our Threat…

831 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question