How to block until an event is fired in c#

前端 未结 4 684
孤街浪徒
孤街浪徒 2020-12-23 09:29

After asking this question, I am wondering if it is possible to wait for an event to be fired, and then get the event data and return part of it. Sort of like this:

4条回答
  •  遥遥无期
    2020-12-23 10:01

    If you're happy to use the Microsoft Reactive Extensions, then this can work nicely:

    public class Foo
    {
        public delegate void MyEventHandler(object source, MessageEventArgs args);
        public event MyEventHandler _event;
        public string ReadLine()
        {
            return Observable
                .FromEventPattern(
                    h => this._event += h,
                    h => this._event -= h)
                .Select(ep => ep.EventArgs.Message)
                .First();
        }
        public void SendLine(string message)
        {
            _event(this, new MessageEventArgs() { Message = message });
        }
    }
    
    public class MessageEventArgs : EventArgs
    {
        public string Message;
    }
    

    I can use it like this:

    var foo = new Foo();
    
    ThreadPoolScheduler.Instance
        .Schedule(
            TimeSpan.FromSeconds(5.0),
            () => foo.SendLine("Bar!"));
    
    var resp = foo.ReadLine();
    
    Console.WriteLine(resp);
    

    I needed to call the SendLine message on a different thread to avoid locking, but this code shows that it works as expected.

提交回复
热议问题