c# - 如何等待循环内的所有踏板完成运行

标签 c# multithreading

以下代码将调用函数名称 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/

相关文章:

c# - 文件名路径中撇号代码的特殊字符替换

C#和Kinect手势时间

c# - WinForms 相当于 WPF 的 IsHitTestVisible

java - 为什么我的无限会导致程序的其余部分卡住,即使它位于单独的线程上?

android - 每次创建新线程时都会添加到主线程组

C# 根据字符串同步线程

c# - 如何在 C# 中引发事件 - 最佳方法

c# - 如何使用 C# 在 cookie 中添加/删除/替换 LIST

python - Django 中的中间件是线程安全的吗?

java - 使用信号量打印 2 个线程的替代输出