Let's suppose I have this piece of code.
foreach(string value in myList)
{
string result = TimeConsumingTask(value);
//update UI
listBox.Add(result);
}
I want to move string result = TimeConsumingTask(value);
to some background thread. What is the simplest yet efficient way of moving this to background thread if
- Order does matter
- Order doesn't matter
A simple way to guarantee order is to do all the TimeConsumingTasks sequentially in the same background thread.
This may take slightly longer than executing multiple TimeConsumingTasks on multiple threads, but saves you a lot of headache trying to synchronize the results and produce output in the required order.
If your main objective is to free up the UI so the user can continue working on something else, the difference in completion time between using one thread and multiple threads is probably negligible, so go the simplest route - use a single background thread for all the TimeConsumingTasks.
If your main objective is to make the computation of the TimeConsumingTasks complete more quickly, then running multiple threads is probably the better approach since it is more likely to take advantage of multiple cores and execute some of the work in parallel.
To preserve order in the multiple threads case, you will have to order the results yourself. You can either maintain an accumulator temp list and insert each result into it at the result's appropriate location in the list (if the location / index is easily computed or known), or you add an additional processing step after all the threads have completed to coalesce the multiple results into the final output in the desired order. In parallel and distributed computing circles, the process of splitting a problem into multiple chunks to be completed in parallel and then combining the results into a coherent order is called "map reduction".