Solved

multithreading in a loop C#

Posted on 2013-12-16
8
340 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
 
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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Chat Room 1 43
Round up to 100% in .NET 10 84
Convert to Hour/minute textbox and compare 3 52
ADO.NET ENTITY DATA MODEL 3 30
Summary: Persistence is the capability of an application to store the state of objects and recover it when necessary. This article compares the two common types of serialization in aspects of data access, readability, and runtime cost. A ready-to…
This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, just open a new email message. In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
Internet Business Fax to Email Made Easy - With  eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, f…

911 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

Need Help in Real-Time?

Connect with top rated Experts

24 Experts available now in Live!

Get 1:1 Help Now