Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parallel Processing/Parallel Programming in C#

I need to process more than one function that goes and performs results returning the same type of records. I am using c# under visual studio 2010 considering the functions i have are:

class Search{
public list<wrecords> GetrecordsofAAA(string term);
public list<wrecords> GetrecordsofBBB(string term);
public list<wrecords> GetrecordsofCCC(string term);
}

and im calling the functions this way

list<wrecords> records1 = Search.GetrecordsofAAA(heart);
list<wrecords> records2 = Search.GetrecordsofBBB(heart);
list<wrecords> records3 = Search.GetrecordsofCCC(heart);

this is series processing.

I need records1, records2 and records 3 to be filled simultaneously, if possible.

like image 779
Ghassan Avatar asked Dec 17 '22 09:12

Ghassan


2 Answers

Take a look at the Task Parallel Library (TPL) which was introduced in .NET Framework 4 (ie. with Visual Studio 2010). More specifically, in terms of the TPL, your problem can be solved with task parallelism.

Now, I'm not an TPL expert myself at all, but documentation suggests that you should be able to do what you want with Parallel.Invoke:

using System.Threading.Tasks;
…

List<wrecords> records1 = null;
List<wrecords> records2 = null;
List<wrecords> records3 = null;
// ^ Initialize these to any default value to prevent a compile-time error.
//   The compiler cannot know that below delegates will actually be called,
//   so without the initialization you would soon get a "use of unassigned
//   variable" error.

Parallel.Invoke(
    () => { records1 = Search.GetrecordsofAAA(heart); },
    () => { records2 = Search.GetrecordsofBBB(heart); },
    () => { records3 = Search.GetrecordsofCCC(heart); }
);

P.S.: Once your methods execute in parallel, you need to make sure that none of them has any side effects that could result in the other methods not functioning properly. (For instance, if these methods read and modify the same static fields belonging to your Search class, that could lead to problems.)

like image 189
stakx - no longer contributing Avatar answered Jan 01 '23 16:01

stakx - no longer contributing


//make a list of the search functions you want to call.
var Searches = new List<string, Func<string, IEnumerable<wrecord>>> {
    a => GetrecordsofAAA(a),
    a => GetrecordsofBBB(a),
    a => GetrecordsofCCC(a),
}

//Execute them in parallel and collect the results as lists of lists of wrecord
IEnumerable<IEnumerable<wrecord>> result = 
    Searches.AsParallel().Select(a => a(heart));
like image 29
albertjan Avatar answered Jan 01 '23 16:01

albertjan