From 6e990e43127adb6cd85fc448d49de5b49d62944f Mon Sep 17 00:00:00 2001 From: Whit Waldo Date: Tue, 18 Mar 2025 10:05:23 -0500 Subject: [PATCH] Added .NET streaming subscription example to pubsub page Signed-off-by: Whit Waldo --- .../pubsub/subscription-methods.md | 50 ++++++++++++++++++- 1 file changed, 49 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 5c31057ee..406368b41 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 @@ -203,7 +203,55 @@ 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 Python Go >}} +{{< tabs .NET Python Go >}} + +{{% codetab %}} + +You can use the `SubscribeAsync` method on the `DaprPublishSubscribeClient` to configure the message handler to use to pull messages from the stream. + +```c# +using System.Text; +using Dapr.Messaging.PublishSubscribe; +using Dapr.Messaging.PublishSubscribe.Extensions; + +var builder = WebApplication.CreateBuilder(args); +builder.Services.AddDaprPubSubClient(); +var app = builder.Build(); + +var messagingClient = app.Services.GetRequiredService(); + +//Create a dynamic streaming subscription and subscribe with a timeout of 30 seconds and 10 seconds for message handling +var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(30)); +var subscription = await messagingClient.SubscribeAsync("pubsub", "myTopic", + new DaprSubscriptionOptions(new MessageHandlingPolicy(TimeSpan.FromSeconds(10), TopicResponseAction.Retry)), + HandleMessageAsync, cancellationTokenSource.Token); + +await Task.Delay(TimeSpan.FromMinutes(1)); + +//When you're done with the subscription, simply dispose of it +await subscription.DisposeAsync(); +return; + +//Process each message returned from the subscription +Task HandleMessageAsync(TopicMessage message, CancellationToken cancellationToken = default) +{ + try + { + //Do something with the message + Console.WriteLine(Encoding.UTF8.GetString(message.Data.Span)); + return Task.FromResult(TopicResponseAction.Success); + } + catch + { + return Task.FromResult(TopicResponseAction.Retry); + } +} +``` + +[Learn more about streaming subscriptions using the .NET SDK client.]({{< ref "dotnet-messaging-pubsub-howto.md" >}}) + +{{% /codetab %}} + {{% codetab %}}