waf*_*ers 2 .net c# multithreading asynchronous
我试图在一个单独的线程中运行for循环,以便UI应该响应并且进度条是可见的.
问题是我不知道该怎么做:).在此代码中,进程在单独的线程中启动,但代码的下一部分同时执行.将显示messageBox并且永远不会返回结果(例如,永远不会设置列表框的选定索引属性).
即使我使用"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!");
}
Run Code Online (Sandbox Code Playgroud)
谁能告诉我如何使用带有"for"或"foreach"循环的多线程?
你需要使用 Task.Wait()
试试这个:
TaskEx.Wait();
if (IsIndexMatched == true)
stkPanelGoto.Visibility = Visibility.Collapsed;
Run Code Online (Sandbox Code Playgroud)
如果要限制等待时间,可以给出Wait()时间参数或TimeSpan,例如:
TaskEx.Wait(10000)
Run Code Online (Sandbox Code Playgroud)
您也可以使用CancellationToken,
或者CancellationToken和时间限制的组合
阅读MSDN上的所有选项:http:
//msdn.microsoft.com/en-us/library/dd235635.aspx