处理AcceptMessageSessionAsync和ReceiveAsync的简便方法

时间:2014-01-21 17:32:43

标签: c#-4.0 task-parallel-library servicebus azureservicebus

尝试跳转到Windows Server ServiceBus 1.1代码库并采用新的TPL异步方法。但我找不到一个简单的方法来为消息会话启动N个处理程序(可能有100个左右的并发会话)。因此,对以下代码获得一些反馈会很棒,任何有关更简单方法的建议都会很棒...请注意,为了问题目的,请尽量保持代码示例的简单。

///example usage
SubscriptionClient subClient = SubscriptionClient.Create(TopicName, SubscriptionName);

subClient.HandleSessions(5, msg =>
        {
            Console.WriteLine(string.Format("Processing recived Message: SessionId = {0}, Body = {1}",
                msg.SessionId,
                msg.GetBody<string>()));
            msg.Complete();
        });


public static class SubscriptionClientExtensions
{
    public static void HandleSessions (this SubscriptionClient sc, Int32 numberOfSessions, Action<BrokeredMessage> handler)
    {
        Action<Task<MessageSession>> sessionAction = null;
        Action<Task<BrokeredMessage>> msgHandler = null;

        sessionAction = new Action<Task<MessageSession>>(tMS =>
        {
            if (tMS.IsFaulted) // session timed out - repeat
            {
                sc.AcceptMessageSessionAsync().ContinueWith(sessionAction);
                return;
            }

            MessageSession msgSession = null;
            try
            {
                msgSession = tMS.Result;
            }
            catch (Exception)
            {
                return; // task cancelation exception
            }

            msgHandler = new Action<Task<BrokeredMessage>>(taskBM =>
            {
                if (taskBM.IsFaulted)
                    return;

                BrokeredMessage bMsg = null;
                try
                {
                    bMsg = taskBM.Result;
                }
                catch (Exception)
                {
                    return; // task cancelation exception
                }

                if (bMsg == null)
                {
                    sc.AcceptMessageSessionAsync().ContinueWith(sessionAction); // session is dead
                    return;
                }

                handler(bMsg); // client code to handle the message

                msgSession.ReceiveAsync(TimeSpan.FromSeconds(5)).ContinueWith(msgHandler); // repeat
            });

            msgSession.ReceiveAsync(TimeSpan.FromSeconds(5)).ContinueWith(msgHandler); // start listening
        });

        for (Int32 nIndex = 0; nIndex < numberOfSessions; nIndex++)
        {
            sc.AcceptMessageSessionAsync().ContinueWith(sessionAction);
        }
    }
}

0 个答案:

没有答案
相关问题