Pittsburgh DBA
Pittsburgh DBA

Reputation: 6773

Azure Service Bus - SubscriptionClient.AcceptMessageSession() vs. SubscriptionClient.BeginAcceptMessageSession()

In the Azure Service Bus namespace, there is a SubscriptionClient type, with a method to initiate a MessageSession in this manner:-

MessageSession session = subscriptionClient.AcceptMessageSession(...);

This is the synchronous version, and it returns a MessageSession. The library also provides an asynchronous version, BeginAcceptMessageSession(). This one is tripping me up, because it invokes a callback, passing in an IAsyncResult and whatever state object you wish to pass. In my case, I am passing the SubscriptionClient instance, so that I can invoke EndAcceptMessageSession() on the SubscriptionClient. BeginAcceptMessageSession() has a return type of void.

How can I access the MessageSession that is accepted via BeginAcceptMessageSession()? All I get back in the callback's result parameter is my SubscriptionClient instance, which I need in order to terminate the BeginAcceptMessageSession() via EndAcceptMessageSession().

The MessageSession reference is nowhere to be found. The documentation is no help in this regard. Searching on Google only reveals a scant 3 pages of search results, most of which is simply the online description of the method itself from MSDN. I looked in AsyncManager.Parameters and it is also empty.

Does anyone know how BeginAcceptMessageSession() is supposed to be invoked so that I can get a reference to the MessageSession thus created?

Upvotes: 2

Views: 1446

Answers (1)

Sandrino Di Mattia
Sandrino Di Mattia

Reputation: 24895

You should invoke the method like this:

  1. Call the begin method with a method that accepts the IAsyncResult and the SubscriptionClient.
  2. In the other method (AcceptDone in this case), call EndAcceptMessageSession with the IAsyncResult to get the MessageSession

What you see here is an standard implementation of the Asynchronous Programming Model.

    private static void Do()
    {
        SubscriptionClient client = ...
        client.BeginAcceptMessageSession(AcceptDone, client);
    }

    public static void AcceptDone(IAsyncResult result)
    {
        var subscriptionClient = result.AsyncState as SubscriptionClient;
        if (subscriptionClient == null)
        {
            Console.WriteLine("Async Subscriber got no data.");
            return;
        }

        var session = subscriptionClient.EndAcceptMessageSession(result);
        ...

        subscriptionClient.Close();
    }

Upvotes: 2

Related Questions