我正在编写一些响应Azure Service Bus Queue的功能。这当前在指定队列上轮询,OnMessage触发对原始类中调用它的方法的回调:
partial class Class1
{
private void BeginProcessing()
{
serviceBusHelper.Listen(QueueType.Inbound, HandleTransaction);
}
private bool HandleTransaction(BrokeredMessage message)
{
...
}
}
然后是服务总线助手类:
public class ServiceBusHelper : IServiceBusHelper
{
ManualResetEvent CompletedResetEvent = new ManualResetEvent(false);
public void Listen(QueueType queue, Action<BrokeredMessage> callback)
{
switch (queue)
{
case QueueType.Inbound:
inboundClient.OnMessage(message =>
{
try
{
callback(message);
}
catch (Exception ex)
{
...
}
CompletedResetEvent.WaitOne();
});
break;
...
}
}
它正确连接到azure服务总线队列并检索消息,但回调似乎永远不会实际触发。我想要实现的是一个服务,它将持续响应OnMessage事件,触发一个新的worker(从class1中),尽管OnMessage实际上是从ServiceBusHelper类触发的。
答案 0 :(得分:0)
回调似乎永远不会触发。
为了重现这个问题,我在一个控制台应用程序中进行测试,我的代码中包含以下代码,这样可以正常工作。
public static void processmessage()
{
string connectionString = "{connectionstring here}";
var queueName = "{queue name}";
var client = QueueClient.CreateFromConnectionString(connectionString, queueName);
var options = new OnMessageOptions();
options.AutoComplete = false;
try
{
client.OnMessage(message =>
{
HandleTransaction(message);
}, options);
}
catch (Exception)
{
}
}
private static void HandleTransaction(BrokeredMessage message)
{
Console.WriteLine(String.Format("Message body: {0}", message.GetBody<String>()));
}
如果可能,您可以尝试将private bool HandleTransaction(BrokeredMessage message)
修改为make it return void private void HandleTransaction(BrokeredMessage message)
,并检查其是否正常。
答案 1 :(得分:0)
所以我设法通过修改异步OnMessage对应来实现这一点。我认为根本原因与未指定OnMessage的OnMessageOptions或者CompletedResetEvent没有相互影响我的预期有关。
public void Listen(QueueType queue, Action<BrokeredMessage> callback)
{
OnMessageOptions options = new OnMessageOptions
{
MaxConcurrentCalls = maxConcurrent,
AutoComplete = false
};
switch (queue)
{
case QueueType.Inbound:
inboundClient.OnMessageAsync(async message =>
{
bool shouldAbandon = false;
try
{
callback(message);
// complete if successful processing
await message.CompleteAsync();
}
catch (Exception ex)
{
shouldAbandon = true;
Debug.WriteLine(ex);
}
if (shouldAbandon)
{
await m.AbandonAsync();
}
}, options);
break;
...
}
}