Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

make AsyncSubscriber with await. #129

Open
alexpantyukhin opened this issue Jul 26, 2019 · 4 comments
Open

make AsyncSubscriber with await. #129

alexpantyukhin opened this issue Jul 26, 2019 · 4 comments

Comments

@alexpantyukhin
Copy link

I reviewed the Subscribe method usages: Subscribe(string subject, StanSubscriptionOptions options, EventHandler<StanMsgHandlerArgs> handler);

I think we can have some kind more improvements. Please see the following code:

var cf = new StanConnectionFactory();
using (var c = cf.CreateConnection("test-cluster", "subscriber", opt))
{
    var asyncSubscriber = c.AsyncSubscriber(request.Topic)
    ConsumedResult<byte[]> consumedResult = null;
    do
    {
            var consumedResult = await asyncSubscriber.Consume();
            // handle consumed result
    }
    while (consumedResult.Message != null);
    asyncSubscriber.Unsubscribe();
}
@ColinSullivan1
Copy link
Member

I do like that pattern. Would you want to make a contribution?

@alexpantyukhin
Copy link
Author

If I will have time soon I would like to do it. But also I don't mind if it will be implemented by someone else :)

@RichiCoder1
Copy link

C#8 now provides Asynchronous Streams which may be an even more natural fit for this, though you'd only be able to expose it to .Net Standard 2.1 & .Net Core 3 targets.

@johnsusi
Copy link

Here is another approach using channels.

var channel = Channel.CreateUnbounded<StanMsg>();
using var connection = new StanConnectionFactory().CreateConnection("test-cluster", "test-client");
using var subscription = connection.Subscribe("topic", (sender, args) =>
{            
    while (!channel.Writer.TryWrite(args.Message));
});

await foreach (var msg in channel.Reader.ReadAllAsync())
{
    // do work
}

https://devblogs.microsoft.com/dotnet/an-introduction-to-system-threading-channels/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants