开发者

Threads in C# [Question]

Thread1/2: do TotalThreads-- on their exit

int开发者_如何学Python TotalThreads = 2;

void AsyncFunc() {
 // run thread for Func()
}

void Func() {
 // run Thread1 
 // run Thread2
 while(TotalThreads > 0) { /* do nothing */ }
 // some code
}  

is that bad design?


If you are creating new threads using System.Threading.Thread, you can use Thread.Join on each thread instance. This will block the main thread until the running threads have completed.

Based on your comments, this example should match your requirement.

using System;
using System.Threading;

namespace ConsoleApplication1
{
  class Program
  {
    [STAThread]
    static void Main(string[] args)
    {

      Thread t1 = new Thread(new ThreadStart(AsyncFunc));
      Thread t2 = new Thread(new ThreadStart(AsyncFunc));

      t1.Start();
      t2.Start();

      // Wait here for the 2 threads to complete
      t1.Join();
      t2.Join();

      Console.WriteLine("Done");
      Console.ReadKey();
    }


    static void AsyncFunc()
    {
      Thread.Sleep(2000);
    }

  }
}  


I'm assuming this implies you're decrementing TotalThreads inside each thread as it completes? You'd have to synchronize access to the variable otherwise you'll have a race-condition.

In general, there are better ways of doing things. The simplest is to explicitly join each thread at the end of your code, to wait for them to terminate:

thread1.Join()
thread2.Join()

If you want to do this for multiple threads, you could put them all into a List, and then Join them all inside a foreach loop.

If you just want to run a couple of AsyncFunc, an even nicer way is using the Parallel Extensions, available in .NET 4.0, or backported to 3.5 in the Reactive Extensions library:

Parallel.Invoke(AsyncFunc, AsyncFunc); 

This will run two copies of the function in parallel, and return after they both complete.


Using a "busy-wait" (that's what you are doing with your while loop) is never a good idea. Let each thread signal when it's finished via a delegate and decrement your totalthreads counter in that event handler (Don't forget to lock the counter during that operation).

When all threads are finished, call another function that will continue with whatever you want to do next.


Look into Thread.Join for lets-wait-for-threads-to-finish synchronization.


Sounds like you want the Thread.Join() method.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜