以下代码将调用函数名称 dictionary_match
。此功能将运行几秒钟。因此,我使用以下代码为我想用字典检查的每个单词并行调用此函数。你能告诉我如何等到函数的所有 5 个实例都运行完才能查看结果(而不是必须使用 Thread.Sleep(6000);
如下所示)吗?
string[] rand_word = {apple, bannnana, cat, dog, eatttt}//5 words to check with the dictionary. Amount of words in here can vary later, that's why I am using a loop bellow
string likelihood = 0;
foreach (string line in rand_word)
{
Thread thread1 = new Thread(new ThreadStart(() => dictionary_match(line, ref likelihood)));
thread1.Start();
Console.WriteLine("Value of likelihood Inside the Loop= " + likelihood); //Will show 0 since the dictionary_match function isn't finished running
}
Console.WriteLine("Value of likelihood after the Loop= " + likelihood);//Will give 0 since the dictionary_match function isn't finished
Thread.Sleep(6000);
Console.WriteLine("Final Value likelihood = " + likelihood); //After pausing for a while, dictionary_match function finished processing and gives an appropriate value for likelihood variable
void dictionary_match(string word, ref double likelihood)//To see if the word is presented in the dictionary
{
//after processing for few seconds, if the word is present in the dictionary
likelihood++;
}
最佳答案
我会为此使用 Task
:
string[] rand_word = {apple, bannnana, cat, dog, eatttt}//5 words to check with the dictionary. Amount of words in here can vary later, that's why I am using a loop bellow
string likelihood = 0;
var tasks = new List<Task>();
foreach (string line in rand_word)
{
tasks.Add(Task.Factory.StartNew(() =>
{
dictionary_match(line, ref likelihood)));
Console.WriteLine("Value of likelihood Inside the Loop= "
+ likelihood);
});
}
Console.WriteLine("Value of likelihood after the Loop= " + likelihood)
Task.WaitAll(tasks);
Console.WriteLine("Final Value likelihood = " + likelihood);
原因是任务比线程轻 - 在这种情况下 Task.WaitAll(..)
非常方便
关于c# - 如何等待循环内的所有踏板完成运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20020311/