How do I wait for a C# event to be raised?

前端 未结 5 1751
再見小時候
再見小時候 2021-01-01 23:38

I have a Sender class that sends a Message on a IChannel:

public class MessageEventArgs : EventArgs {
  public Message         


        
5条回答
  •  猫巷女王i
    2021-01-01 23:57

    Useful sample with AutoResetEvent:

        using System;
        using System.Threading;
    
        class WaitOne
        {
            static AutoResetEvent autoEvent = new AutoResetEvent(false);
    
            static void Main()
            {
                Console.WriteLine("Main starting.");
    
                ThreadPool.QueueUserWorkItem(
                    new WaitCallback(WorkMethod), autoEvent);
    
                // Wait for work method to signal.
                autoEvent.WaitOne();
                Console.WriteLine("Work method signaled.\nMain ending.");
            }
    
            static void WorkMethod(object stateInfo) 
            {
                Console.WriteLine("Work starting.");
    
                // Simulate time spent working.
                Thread.Sleep(new Random().Next(100, 2000));
    
                // Signal that work is finished.
                Console.WriteLine("Work ending.");
                ((AutoResetEvent)stateInfo).Set();
            }
        }
    

提交回复
热议问题