parallel calls - How to Identify which call failed?

Kannan1212

New member
Joined
Apr 11, 2020
Messages
4
Programming Experience
1-3
I am new to Parallel call in .Net core, please help me.

I am making Parallel call, so I would like to know here if any calls fails in If one of out of many calls fails or all calls failed then we should write to logs specific which Permanent ID got failed. Please help me how to Identify which one failed

C#:
foreach (var permanentId in permanentIds)
{
    Request1 request = new Request1 ()
    {
        AccountID =  permanentId // "02134665300468820"
    };

    tasks.Add(ModelServiceProcessing(request).ContinueWith((TResult) => ServiceList.Add(TResult.Result)));
}

await Task.WhenAll(tasks.ToArray());
 
Last edited by a moderator:
I am able to solve using like below -
C#:
Dictionary<Task, string> taskAccountMap = new Dictionary<Task, string>();

foreach (var permanentId in permanentIds)
{
    Request1 request = new Request1()
    {
        AccountID =  permanentId // "02134665300468820"
    };

    Task requestTask = ModelServiceProcessing(request).ContinueWith((TResult) => ServiceList.Add(TResult.Result));
    taskAccountMap[requestTask] = permanentId;
    tasks.Add(requestTask);
}
 
I already formatted the code in your first post and specifically asked you to format code snippets in future and you have ignored that. Please do us the courtesy of formatting your code for readability in future.
 
@Kannan1212: Although your solution in post #3 may work, it feels like such a kludge. Here we are in a modern world using objects, multiple threads, asynchronous code, and parallism, and then we revert back to using parallel arrays or expensive dictionaries to map which id was being handled by which task.

The ideal solution is for your ModelServiceProcessing() to return a Task<TResult> where the TResult also contains the ID. This keeps all associated information together and you don't need to worry about the lifetime of your dictionary and the tasks it contains. It also is more logical that the task and ID are together instead of trying to go find the task in the dictionary to figure out what ID was passed to that task.

A slightly less ideal solution, but will work exactly for these cases when you cannot change the ModelServiceProcessing() is to use a Tuple to keep the ID and Task together. Yes, it may seem like a kludge because it is a kludge, but it is less of a kludge than that dictionary approach. Furthermore more, a list of Tuples is less expensive than a dictionary of IDs mapping to Tasks in terms of memory and CPU.
 
Last edited:
Back
Top Bottom