2013-08-09 17 views
12

Come è possibile attendere il numero di impulsi n?Lasciare un thread in attesa per n numero di impulsi

… // do something 
waiter.WaitForNotifications(); 

voglio il filo sopra di aspettare che notifica n volte (da n diverse filettature o n volte dallo stesso filo).

Credo che ci sia un tipo di contatore per farlo, ma non riesco a trovarlo.

risposta

22

Date un'occhiata al CountdownEvent Class:

CountdownEvent Classe

Rappresenta una primitiva di sincronizzazione che viene data quando il suo conteggio raggiunge lo zero.

Esempio:

CountdownEvent waiter = new CountdownEvent(n); 

// notifying thread 
waiter.Signal(); 

// waiting thread 
waiter.Wait(); 
+0

Thx, era esattamente quello che stavo cercando – Toto

8

Utilizzando un semplice ManualResetEvent e Interlocked.Decrement

class SimpleCountdown 
{ 
    private readonly ManualResetEvent mre = new ManualResetEvent(false); 

    private int remainingPulses; 

    public int RemainingPulses 
    { 
     get 
     { 
      // Note that this value could be not "correct" 
      // You would need to do a 
      // Thread.VolatileRead(ref this.remainingPulses); 
      return this.remainingPulses; 
     } 
    } 

    public SimpleCountdown(int pulses) 
    { 
     this.remainingPulses = pulses; 
    } 

    public void Wait() 
    { 
     this.mre.WaitOne(); 
    } 

    public bool Pulse() 
    { 
     if (Interlocked.Decrement(ref this.remainingPulses) == 0) 
     { 
      mre.Set(); 
      return true; 
     } 

     return false; 
    } 
} 

public static SimpleCountdown sc = new SimpleCountdown(10); 

public static void Waiter() 
{ 
    sc.Wait(); 
    Console.WriteLine("Finished waiting"); 
} 

public static void Main() 
{ 
    new Thread(Waiter).Start(); 

    while (true) 
    { 
     // Press 10 keys 
     Console.ReadKey(); 

     sc.Pulse(); 
    } 
} 

Nota che, alla fine, questo il tuo problema è spesso collegato a questo altro problema: Workaround for the WaitHandle.WaitAll 64 handle limit?

La mia soluzione è bene se non hai .NET> = 4 (perché l'altra soluzione, CountdownEvent, è stata introdotta in .NET 4)

Problemi correlati