Skip to content

Commit f8095d8

Browse files
committed
Avoid somewhat complicated if logic.
1 parent f60fa9f commit f8095d8

File tree

1 file changed

+25
-18
lines changed

1 file changed

+25
-18
lines changed

dotnet/PublisherConfirms/PublisherConfirms.cs

+25-18
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
1-
using System.Buffers.Binary;
1+
using RabbitMQ.Client;
2+
using System.Buffers.Binary;
23
using System.Diagnostics;
34
using System.Text;
4-
using RabbitMQ.Client;
55

66
const ushort MAX_OUTSTANDING_CONFIRMS = 256;
77

@@ -94,27 +94,34 @@ async Task PublishMessagesInBatchAsync()
9494
ValueTask publishTask = channel.BasicPublishAsync(exchange: string.Empty, routingKey: queueName, body: body, mandatory: true, basicProperties: props);
9595
publishTasks.Add(publishTask);
9696

97-
// NOTE: [publishTasks] should be published after the final message has been added,
98-
// even if the # of tasks it contains isn't equal to [batchSize].
99-
if (publishTasks.Count == batchSize || i+1 == MESSAGE_COUNT)
97+
await MaybeAwaitPublishes(publishTasks, batchSize);
98+
}
99+
100+
// Await any remaining tasks in case message count was not
101+
// evenly divisible by batch size.
102+
await MaybeAwaitPublishes(publishTasks, 0);
103+
104+
sw.Stop();
105+
Console.WriteLine($"{DateTime.Now} [INFO] published {MESSAGE_COUNT:N0} messages in batch in {sw.ElapsedMilliseconds:N0} ms");
106+
}
107+
108+
static async Task MaybeAwaitPublishes(List<ValueTask> publishTasks, int batchSize)
109+
{
110+
if (publishTasks.Count >= batchSize)
111+
{
112+
foreach (ValueTask pt in publishTasks)
100113
{
101-
foreach (ValueTask pt in publishTasks)
114+
try
102115
{
103-
try
104-
{
105-
await pt;
106-
}
107-
catch (Exception ex)
108-
{
109-
Console.Error.WriteLine($"{DateTime.Now} [ERROR] saw nack or return, ex: '{ex}'");
110-
}
116+
await pt;
117+
}
118+
catch (Exception ex)
119+
{
120+
Console.Error.WriteLine($"{DateTime.Now} [ERROR] saw nack or return, ex: '{ex}'");
111121
}
112-
publishTasks.Clear();
113122
}
123+
publishTasks.Clear();
114124
}
115-
116-
sw.Stop();
117-
Console.WriteLine($"{DateTime.Now} [INFO] published {MESSAGE_COUNT:N0} messages in batch in {sw.ElapsedMilliseconds:N0} ms");
118125
}
119126

120127
async Task HandlePublishConfirmsAsynchronously()

0 commit comments

Comments
 (0)