Skip to content

Instantly share code, notes, and snippets.

@clemensv
Created February 13, 2017 15:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save clemensv/650361dc37b1eb77a91d00dbc1611288 to your computer and use it in GitHub Desktop.
Save clemensv/650361dc37b1eb77a91d00dbc1611288 to your computer and use it in GitHub Desktop.
// Copyright (c) Microsoft.
// Licensed under the MIT license.
namespace ConsoleApplication6
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
using Microsoft.ServiceBus.Messaging;
class Program
{
async Task Send1KBadly()
{
var payload = new byte[1024];
var mfc =
MessagingFactory.CreateFromConnectionString(
"...");
var qc = mfc.CreateQueueClient("queue");
Console.WriteLine("Bad loop");
// connect and link setup
await qc.SendAsync(new BrokeredMessage(new MemoryStream(payload)));
var lsw = new Stopwatch();
lsw.Start();
await qc.SendAsync(new BrokeredMessage(new MemoryStream(payload)));
lsw.Stop();
Console.WriteLine("RTL {0} msec", lsw.ElapsedMilliseconds);
Console.WriteLine(".");
var sw = new Stopwatch();
sw.Start();
// loop
for (int i = 0; i < 100; i++)
{
await qc.SendAsync(new BrokeredMessage(new MemoryStream(payload)));
}
sw.Stop();
await qc.CloseAsync();
await mfc.CloseAsync();
Console.WriteLine("Elapsed {0} sec", sw.ElapsedMilliseconds/1000.0);
}
async Task Send1KWell()
{
var payload = new byte[1024];
var mfc =
MessagingFactory.CreateFromConnectionString(
"...");
var qc = mfc.CreateQueueClient("queue");
Console.WriteLine("Good loop");
// connect and link setup
await qc.SendAsync(new BrokeredMessage(new MemoryStream(payload)));
Console.WriteLine(".");
var tl = new List<Task>();
var sw = new Stopwatch();
sw.Start();
// loop
for (int i = 0; i < 100; i++)
{
tl.Add(qc.SendAsync(new BrokeredMessage(new MemoryStream(payload))));
}
await Task.WhenAll(tl.ToArray());
sw.Stop();
await qc.CloseAsync();
await mfc.CloseAsync();
Console.WriteLine("Elapsed {0} sec", sw.ElapsedMilliseconds/1000.0);
}
static void Main(string[] args)
{
var p = new Program();
p.Send1KBadly().GetAwaiter().GetResult();
p.Send1KWell().GetAwaiter().GetResult();
}
}
}
@pksorensen
Copy link

TPL Dataflow is so underused but makes these things so much more nice.

var block = new ActionBlock(async(payload)=>{
    await qc.SendAsync(new BrokeredMessage(new MemoryStream(payload)));
}, new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = DataflowBlockOptions.Unbounded });

for (int i = 0; i < 100; i++)
{
     await block.SendAsync(payload);
}
block.Complete();
await block.Completion;

and it gives alot of options to configure how many concurrent messages it should be sending ect.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment