I have a list actions calling different methods. All actions will need to run in different threads in parallel using Parallel.ForEach. All actions will return a bunch of info as an object Result. All Results are added to a log using a lock on the log.
My question and possible issue is: can the action methods have a return value to be retrieved and used inside the Parallel.ForEach and how would that be done? Also, how could the Result be safely used without being overwritten every time a thread finishes execution while another result is waiting for the log to be updated?
My current simplified code looks something like this:
private Log _log;
private void DoParallelWork()
{
List<Action> actions = new List<Action> { Action1, Action2, Action3, ...etc };
Result result = new Result();
System.Threading.Tasks.Parallel.ForEach(actions , action =>
{
**result** = action(); // How can I get the result back to the ForEach?
lock (_log)
{
UpdateLog(result);
}
});
}
private Result Action1() // same structure for Action2, 3, ...etc
{
return [call to the db to execute a stored procedure returning a Result object];
}
private void UpdateLog(Result result)
{
// update _log based on result
}
Thanks for helping out
new List<Func<Result>>