public async Task <int> PublishBatchMessagesAsync(string projectId, string topicId, IEnumerable <string> messageTexts) { TopicName topicName = TopicName.FromProjectTopic(projectId, topicId); // Default Settings: // byteCountThreshold: 1000000 // elementCountThreshold: 100 // delayThreshold: 10 milliseconds var customSettings = new PublisherClient.Settings { BatchingSettings = new BatchingSettings( elementCountThreshold: 50, byteCountThreshold: 10240, delayThreshold: TimeSpan.FromMilliseconds(500)) }; PublisherClient publisher = await PublisherClient.CreateAsync(topicName, settings : customSettings); int publishedMessageCount = 0; var publishTasks = messageTexts.Select(async text => { try { string message = await publisher.PublishAsync(text); Console.WriteLine($"Published message {message}"); Interlocked.Increment(ref publishedMessageCount); } catch (Exception exception) { Console.WriteLine($"An error occurred when publishing message {text}: {exception.Message}"); } }); await Task.WhenAll(publishTasks); return(publishedMessageCount); }
private static Task <PublisherClient> CreatePublisherClientAsync(TopicName topicName, PublisherClient.ClientCreationSettings clientCreationSettings = null, PublisherClient.Settings settings = null) { clientCreationSettings ??= new PublisherClient.ClientCreationSettings(); clientCreationSettings = clientCreationSettings.WithEmulatorDetection(EmulatorDetection.EmulatorOrProduction); return(PublisherClient.CreateAsync(topicName, clientCreationSettings, settings)); }