From 8aa121259ff6182ae8b67fe1e9dcbdf65793b6bd Mon Sep 17 00:00:00 2001 From: Whit Waldo Date: Mon, 16 Sep 2024 14:47:24 -0500 Subject: [PATCH] Added .NET implementation detail for streaming subscription support Signed-off-by: Whit Waldo --- .../pubsub/subscription-methods.md | 42 ++++++++++++++++++- 1 file changed, 41 insertions(+), 1 deletion(-) diff --git a/daprdocs/content/en/developing-applications/building-blocks/pubsub/subscription-methods.md b/daprdocs/content/en/developing-applications/building-blocks/pubsub/subscription-methods.md index 436c1629585..7c90a7c58c6 100644 --- a/daprdocs/content/en/developing-applications/building-blocks/pubsub/subscription-methods.md +++ b/daprdocs/content/en/developing-applications/building-blocks/pubsub/subscription-methods.md @@ -204,7 +204,47 @@ As messages are sent to the given message handler code, there is no concept of r The example below shows the different ways to stream subscribe to a topic. -{{< tabs Go>}} +{{< tabs ".NET" Go>}} + +{{% codetab %}} + +```csharp +using Dapr.Messaging.PublishSubscribe; + +var clientBuilder = new DaprPublishSubscribeClientBuilder(); +var daprMessagingClient = clientBuilder.Build(); + +async Task HandleMessage(TopicMessage message, CancellationToken cancellationToken = default) +{ + try + { + //Do something with the message + Console.WriteLine(Encoding.UTF8.GetString(message.Data.Span)); + + return await Task.FromResult(TopicResponseAction.Success); + } + catch + { + return await Task.FromResult(TopicResponseAction.Retry); + } +} + +//Create a dynamic streaming subscription +var subscription = daprMessagingClient.Register("pubsub", "myTopic", + new DaprSubscriptionOptions(new MessageHandlingPolicy(TimeSpan.FromSeconds(15), TopicResponseAction.Retry)), + HandleMessage, CancellationToken.None); + +//Subscribe to messages on it with a timeout of 30 seconds +var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(30)); +await subscription.SubscribeAsync(cancellationTokenSource.Token); + +await Task.Delay(TimeSpan.FromMinutes(1)); + +//When you're done with the subscription, simply dispose of it +await subscription.DisposeAsync(); +``` + +{{% /codetab %}} {{% codetab %}}