Solved

multithreading in a loop C#

Posted on 2013-12-16
8
335 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
Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

 
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

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

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…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.

759 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

19 Experts available now in Live!

Get 1:1 Help Now