在ServiceFabric中使用ReliableQueue而不进行轮询?

时间:2016-05-09 21:56:10

标签: c# azure azure-service-fabric

我一直在关注Service Fabric中的有状态服务。我一直在挖掘这些例子,特别是WordCount。他们有一个RunAsync方法,在WordCountService内部看起来像这样:

 protected override async Task RunAsync(CancellationToken cancellationToken)
    {
        IReliableQueue<string> inputQueue = await this.StateManager.GetOrAddAsync<IReliableQueue<string>>("inputQueue");

        while (true)
        {
            cancellationToken.ThrowIfCancellationRequested();

            try
            {
                using (ITransaction tx = this.StateManager.CreateTransaction())
                {
                    ConditionalValue<string> dequeuReply = await inputQueue.TryDequeueAsync(tx);

                    if (dequeuReply.HasValue)
                    {
                       //... {more example code here }
                    }
                await Task.Delay(TimeSpan.FromMilliseconds(100), cancellationToken);
            }
            catch (TimeoutException)
            {
                //Service Fabric uses timeouts on collection operations to prevent deadlocks.
                //If this exception is thrown, it means that this transaction was waiting the default
                //amount of time (4 seconds) but was unable to acquire the lock. In this case we simply
                //retry after a random backoff interval. You can also control the timeout via a parameter
                //on the collection operation.
                Thread.Sleep(TimeSpan.FromSeconds(new Random().Next(100, 300)));

                continue;
            }
            catch (Exception exception)
            {
                //For sample code only: simply trace the exception.
                ServiceEventSource.Current.MessageEvent(exception.ToString());
            }
        }
    }

基本上,在此示例中,服务每隔100毫秒轮询ReliableQueue以获取消息。没有民意调查,有没有办法做到这一点?当消息成功添加到ReliableQueue时,我们可以订阅事件或触发的事件吗?

2 个答案:

答案 0 :(得分:1)

我建议您在服务中使用ReliableDispatcher,或者只使用Dispatcher Service

使用 Dispatcher Service ,您可以编写一个方法,只要项目在基础可靠队列中排队,就会调用该方法。

例如:

public override async Task OnItemDispatchedAsync(
    ITransaction transaction,
    int value,
    CancellationToken cancellationToken)
{
    // Do something with the value that has been dequeued
}

Reliable Dispatcher Dispatcher Service 都可以通过NuGet package使用,GitHub上有完整的文档和示例,可以帮助您入门:

答案 1 :(得分:0)

不,目前没有可用于ReliableQueue的活动。您必须轮询新项目。