I am trying to run the for loop in a separate thread so that the UI should be responsive and the progress bar is visible.
The problem is that I don’t know how to do that :). In this code, the process starts in a separate thread, but the next part of the code is executed at the same time. The messageBox is displayed and the results are never returned (e.g. the listbox’s selected index property is never set).
It doesn’t work even if I use, “taskEx.delay()”.
TaskEx.Run(() =>
{
for (int i = 0; i < sResults.Count(); i++)
{
if (sResults.ElementAt(i).DisplayIndexForSearchListBox.Trim().Contains(ayaStr))
{
lstGoto.SelectedIndex = i;
lstGoto_SelectionChanged(lstReadingSearchResults, null);
IsIndexMatched = true;
break;
}
}
});
//TaskEx.delay(1000);
if (IsIndexMatched == true)
stkPanelGoto.Visibility = Visibility.Collapsed;
else //the index didn't match
{
MessagePrompt.ShowMessage("The test'" + ayaStr + "' does not exist.", "Warning!");
}
Could anyone please tell me how can I use multi-threading with a “for” or “foreach” loop?
TaskEx– are you using the async targeting pack for .NET 4.0?In that case, use
await TaskEx.Run(...)– C# 5.0awaitwill wait until the task is completed, but will keep the UI responsive while it is waiting (unlike the.Wait()method).Also, you need to move the
lstGoto.SelectedIndex = i;assignment out of the background thread – accessing UI controls is only allowed on the main thread.A last word of warning: do not use
Count()/ElementAt()repeatedly in a loop – those LINQ methods might end up traversing the whole collection to compute their result. If you need to traverse an IEnumerable by index, it’s much faster to convert it into a List once and then traverse through the list.