4

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

示例代码:

    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"。这是怎么做到的?

4

5 回答 5

1

控制台应用程序 PoC 缓存对所有创建的工作人员的引用,并使用数字变量检查有多少工作人员仍在进行中,当该值达到 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();
        }
    }
}
于 2012-10-15T11:02:54.413 回答
0

您可以使用CountDownEvent类:

例子:

using (CountDownEvent countdownEvent = new CountdownEvent(numberOfThreads))
{
    for (int threadIndex= 0; i < numberOfThreads; threadIndex++)
        ThreadPool.QueueUserWorkItem(
            th =>
            {
                DoWork();
                countdownEvent.Signal();
            }, threadIndex);

    countdownEvent.Wait();
}
Console.WriteLine("All threads complete");
于 2012-10-15T11:14:16.763 回答
0

我用一个易失的整数做的,效果很好。

BackgroundWorker backgroundWorker1;     
    Random ran;
    long runningThreads = 0;
    public void Start()     
    {         
        method();         
       // Console.WriteLine("Threads is finished");     
    }       
    private void method() // recursive method     
    {
        Interlocked.Increment(ref runningThreads);
        Console.WriteLine("New thread started");
        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();             
        }
        Finished();
    }
    private void Finished()
    {
        Interlocked.Decrement(ref runningThreads);
        if (Interlocked.Read(ref runningThreads) == 0)
        {
            Console.WriteLine("Threads is finished");     

        }
    }
于 2012-10-15T13:28:59.417 回答
0

当您决定停止递归时,您可以将回调发布到 GUI 线程上。在我的脑海中,它会是这样的:

if(ran.Next(1,5)!=1)
{
  method();
}
else
{
  Action action=()=>label1.Text = "Threads is finished";
  this.BeginInvoke(action);
}
于 2012-10-15T11:04:21.320 回答
0

1)创建一个更新Label1的方法:

private void WorkFinished()
{
   if(Label1.InvokeRequired)
   {
      Label1.Invoke(WorkFinished);
   }
   else
   {
      Label1.Text = "Threads is finished";
   }
}

2) 从 backgroundWorker1_DoWork 调用 WorkFinished()。

于 2012-10-15T11:04:50.667 回答