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.
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.)
//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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With