Csharp/CSharp Tutorial/Thread/AutoResetEvent — различия между версиями

Материал из .Net Framework эксперт
Перейти к: навигация, поиск
м (1 версия)
 
(нет различий)

Версия 15:31, 26 мая 2010

AutoResetEvent in action

using System;        
using System.Threading;
public class MainClass
{
  public static AutoResetEvent A = new AutoResetEvent(false);
  public static int index = 0;
  
  public static int Main(){
    Timer T = new Timer(new TimerCallback(TimerHandler), null, 5000, 10000);
    A.WaitOne();
    Console.WriteLine("Main Thread event signaled");
    T.Dispose();
    return 0;
  }
  public static void TimerHandler(object state)
  {
    Console.WriteLine("TimerHandler");
    if (index == 5)
      A.Set();
    index++;
    Console.WriteLine(index);
  }
}

Register Wait handle for auto reset event

using System;
using System.Threading;
class MainClass
{
    private static void EventHandler(object state, bool timedout) 
    {
        Console.WriteLine("timedout:"+timedout);
        Console.WriteLine("state:"+state);
        Console.WriteLine(DateTime.Now.ToString("HH:mm:ss.ffff"));
    }
    public static void Main() 
    {
        AutoResetEvent autoEvent = new AutoResetEvent(false);
        string state = "AutoResetEvent signaled.";
        RegisteredWaitHandle handle = ThreadPool.RegisterWaitForSingleObject(
            autoEvent, EventHandler, state, 3000, false);

        Thread.Sleep(5000);
        
        autoEvent.Set();
        
        Console.WriteLine("Unregistering wait operation.");
        handle.Unregister(null);
    }
}
timedout:True
state:AutoResetEvent signaled.
14:14:00.0937
Unregistering wait operation.