Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

awaiting two things in a loop?

How can I await for two or more things (with different types) at the same time? Like in an event loop:

while(true) {
    Letter msg1 = await WaitForLetter();
    //read msg1 and reply.
    SMS msg2 = await WaitForSMS();
    //read msg2 and reply
}

That doesn't look right. The two messages will end up blocking each other?

like image 451
petke Avatar asked Apr 09 '26 10:04

petke


1 Answers

I think that your best option here is to use Microsoft's Reactive Framework (NuGet "Rx-Main"). It works very nicely with Tasks.

Here's the code that you need:

var subscription1 =
    Observable
        .FromAsync(WaitForLetter)
        .Repeat()
        .Subscribe(msg1 =>
        {
            //read msg1 and reply.
        });

var subscription2 =
    Observable
        .FromAsync(WaitForSMS)
        .Repeat()
        .Subscribe(msg2 =>
        {
            //read msg2 and reply
        });

Both run independently of each other and both run asynchronously.

To stop them running simply do this:

subscription1.Dispose();
subscription2.Dispose();

If you actually want them to run like an event loop, whereby messages both come in on the same thread, interspersed with each other, then you can do this:

var eventLoopScheduler = new EventLoopScheduler();

var subscription1 =
    Observable
        .FromAsync(WaitForLetter)
        .Repeat()
        .ObserveOn(eventLoopScheduler)
        .Subscribe(msg1 =>
        {
            //read msg1 and reply.
        });

var subscription2 =
    Observable
        .FromAsync(WaitForSMS)
        .Repeat()
        .ObserveOn(eventLoopScheduler)
        .Subscribe(msg2 =>
        {
            //read msg2 and reply
        });

You have a little more clean-up, but this can be handled nicely with this:

var subscriptions = new CompositeDisposable(
    subscription1,
    subscription2,
    eventLoopScheduler);

//then later

subscriptions.Dispose();
like image 167
Enigmativity Avatar answered Apr 10 '26 23:04

Enigmativity



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!