I have a method which consists of two lists (1. items to search and 2. workers to search with). Each worker takes an item from the list, searches for it, and add the results to a global results list which update the UI thread (a listview).
This is what I came up with so far:
List<Result> allResults = new List<Result>();
var search = new Search(workers);
//Will be full with items to search for
var items= new ConcurrentBag<item>();
while (items.Any())
{
foreach (var worker in workers)
{
if (!items.Any())
break;
IEnumerable<Result> results = null;
Task.Factory.StartNew(() =>
{
if (ct.IsCancellationRequested)
return;
items.TryTake(out Item item);
if (item == null)
return;
results= search.DoWork(worker, item);
}, ct);
if (results?.Any() ?? false)
{
allResults.AddRange(reults);
}
//Update UI thread here?
}
}
The workers should search in parallel and their results added to the global results list. This list will then refresh the UI.
Am I on the right track with the above approach? Will the workers run in parallel? Should I update the UI thread within the task and use BeginInvoke
?