A topic client can send 3 messages with session id (say ABCD) and then sends another 4 messages with session id (XYZ). It is pretty easy to write subscription client to receive all 7 messages with related session ids. However I want the ability to receive messages with session id XYZ only (and don't care about the messages with session id ABCD and don't even want to receive them).
The following example code to receive all messages with all session ids works as expected:
static async Task Main(string[] args)
{
try
{
byte[] messageBody = System.Text.Encoding.Unicode.GetBytes("Hello, world!");
ServiceBusConnectionStringBuilder builder = new ServiceBusConnectionStringBuilder(connectionString);
SubscriptionClient client = new SubscriptionClient(builder, subscriptionName, ReceiveMode.PeekLock);
var sessionHandler = new SessionHandlerOptions(ExceptionHandler);
sessionHandler.AutoComplete = true;
client.RegisterSessionHandler(SessionMessageHandler, sessionHandler);
Console.WriteLine("Press any key to exit!");
Console.ReadKey();
await client.CloseAsync();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
static Task SessionMessageHandler(IMessageSession session, Message message, CancellationToken cancellationToken)
{
var bodyText = System.Text.Encoding.Unicode.GetString(message.Body);
Console.WriteLine($"Session id: {message.SessionId}; Body: {bodyText}");
return Task.CompletedTask;
}
static Task ExceptionHandler(ExceptionReceivedEventArgs args)
{
var context = args.ExceptionReceivedContext;
Console.WriteLine($"Exception context: {context.Action}, {context.ClientId}, {context.Endpoint}, {context.EntityPath}");
Console.WriteLine($"Exception: {args.Exception}");
return Task.CompletedTask;
}
Questions:
The code above is using a session handler that is designed to process multiple sessions and not just a single session. If you'd like to process a single session only with a specific ID, you'd need to use SessionClient
and its AcceptMessageSessionAsync(String)
method that accepts the session ID as the parameter.