c# - 如何跟踪所有线程的完成。 C#

标签 c# multithreading recursion

我需要卡住主线程直到结束递归。 递归深度 = 线程数。

示例代码:

    BackgroundWorker backgroundWorker1;
    Random ran;

    private void Form1_Load(object sender, EventArgs e)
    {
        method();
        label1.Text = "Threads is finished";
    }


    private void method() // recursive method
    {

            Thread.Sleep(100);

            backgroundWorker1 = new BackgroundWorker();

            backgroundWorker1.DoWork +=
                new DoWorkEventHandler(backgroundWorker1_DoWork);
            backgroundWorker1.RunWorkerAsync();               //Beginning new thread
    }

    private void backgroundWorker1_DoWork(object sender,
       DoWorkEventArgs e)
    {
            ran = new Random();
            Thread.Sleep(ran.Next(500, 1000));
            if (ran.Next(1, 5) != 1) // if = 1 then to stop recursion
            {
                method();
            }
    }

当线程完成时,label1.Text 必须具有值 "Threads is finished"。这是怎么做到的?

最佳答案

控制台应用程序 PoC,它缓存对所有创建的 worker 的引用,并使用数字变量检查有多少 worker 仍在进行中,当此值达到 0 时 - 应用程序终止。如有任何问题,请告诉我。

class Program
{
    private static IList<BackgroundWorker> workers;
    private static Random ran;
    private static int activeWorkersCount;

    static void Main(string[] args)
    {            
        workers = new List<BackgroundWorker>();
        DoWork();

        while (activeWorkersCount > 0)
        {
            Thread.Sleep(200);
        }

        Console.WriteLine("Waiting for all workers to finish...");
        Console.ReadLine();
    }

    private static void DoWork() // recursive method
    {
        Thread.Sleep(100);

        var newWorker = new BackgroundWorker();

        newWorker.DoWork += BackgroundWorkerDoWork;
        newWorker.RunWorkerCompleted += (o, e) =>
               {
                  Console.WriteLine("[E] Worker finished");
                  Interlocked.Decrement(ref activeWorkersCount);
               };
        Interlocked.Increment(ref activeWorkersCount);
        newWorker.RunWorkerAsync();
    }

    private static void BackgroundWorkerDoWork(object sender, DoWorkEventArgs e)
    {
        Console.WriteLine("[S] Worker started");
        ran = new Random();
        Thread.Sleep(ran.Next(500, 1000));
        if (ran.Next(1, 5) != 1) // if = 1 then to stop recursion
        {
            DoWork();
        }
    }
}

关于c# - 如何跟踪所有线程的完成。 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12894046/

相关文章:

python - 整数分区的递归公式

ruby - ruby 中的递归乘数

C# Async ApiController 过早关闭 OutputStream

c# - 你将如何声明 DLL 导入签名?

c# - C# 中的条件线程锁

python - 如何使一个线程等待其他线程在python中执行特定任务

java - 删除 Java 二叉搜索树中的方法

c# - 在 C# 中更改波特率而不关闭连接

c# - 将 Cortana channel 添加到 BOT 时凭据不起作用

c++ - 如何在 C++ 中构建执行异步后台任务的对象