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

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

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

public class MessageEventArgs : EventArgs {
  public Message         


        
5条回答
  •  佛祖请我去吃肉
    2021-01-02 00:12

    WaitOne is really the right tool for this job. In short, you want to wait between 0 and MaxWaitInMs milliseconds for a job to complete. You really have two choices, poll for completion or synchronize the threads with some construct that can wait an arbitrary amount of time.

    Since you're well aware of the right way to do this, for posterity I'll post the polling version:

    MessageEventArgs msgArgs = null;
    var callback = (object o, MessageEventArgs args) => {
        msgArgs = args;
    };
    
    _c.MessageReceived += callback;
    _c.Send(m);
    
    int msLeft = MaxWaitInMs;
    while (msgArgs == null || msLeft >= 0) {
        Thread.Sleep(100);
        msLeft -= 100; // you should measure this instead with say, Stopwatch
    }
    
    _c.MessageRecieved -= callback;
    

提交回复
热议问题