Morning.
(Attempting to do): Im tryin to execute several tasks in parallel. Each task runs through a certain section of a text file using a for loop (1st task = rows 1-10. 2nd task = rows 11-20 etc). At the end of each row check, an event is raised and the GUI thread updates the UI ie “X rows have been checked.”
(Stuck on):I dont understand how to do this and yet still be able to handle exceptions correctly. As far as im aware, i need to call
task.Wait();
or
task.WaitAll();
but by calling it, the UI thread just waits there and any events i fire inside the tasks to update the UI just get added the the UI’s queue.
Does anyone know how to get around this?
Note: I apologise in advance if this is stupid but im having some issues with threading.
as the tasks bundle all exceptions into AggregateException and if i call task.Waitall(); the UI thread just seems to wait until the tasks are completed or an exception is thrown.
One option is to attach another task to your task, as a ‘handler’ to deal with any exceptions.
Here’s an example:
Note that the task attached with
ContinueWithhasTaskContinuationOptions.OnlyOnFaulted, which means it will only run if the task it is attached to throws an exception.This way, your exceptions can be handled asynchronously, and you don’t need to wait on anything.
However, since you want to do a parallel for loop, I’d probably do something like:
This way, your main task waits on all the child tasks, but the UI thread which spawned it doesn’t have to wait.
The main thing you have to be sure of is that your
catchclause (or the handling task in previous example) never throws an exception.