C# 在ServiceFabric中使用ReliableQueue而不进行轮询?
我一直在研究服务结构中的有状态服务。我一直在挖掘这些例子,特别是字数。在WordCountService中,它们有一个类似以下内容的RunAsync方法:C# 在ServiceFabric中使用ReliableQueue而不进行轮询?,c#,azure,azure-service-fabric,C#,Azure,Azure Service Fabric,我一直在研究服务结构中的有状态服务。我一直在挖掘这些例子,特别是字数。在WordCountService中,它们有一个类似以下内容的RunAsync方法: protected override async Task RunAsync(CancellationToken cancellationToken) { IReliableQueue<string> inputQueue = await this.StateManager.GetOrAddAsync&l
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());
}
}
}
受保护的覆盖异步任务RunAsync(CancellationToken CancellationToken)
{
IReliableQueue inputQueue=等待这个.StateManager.GetOrAddAsync(“inputQueue”);
while(true)
{
cancellationToken.ThrowIfCancellationRequested();
尝试
{
使用(ITransaction tx=this.StateManager.CreateTransaction())
{
ConditionalValue dequeuReply=await inputQueue.TryDequeueAsync(tx);
if(dequeuReply.HasValue)
{
//…{这里有更多示例代码}
}
等待任务延迟(TimeSpan.From毫秒(100),cancellationToken);
}
捕获(超时异常)
{
//服务结构在收集操作上使用超时来防止死锁。
//如果抛出此异常,则表示此事务正在等待默认值
//时间量(4秒),但无法获取锁。在本例中,我们只需
//在随机退避间隔后重试。您还可以通过参数控制超时
//在收集操作上。
Sleep(TimeSpan.FromSeconds(newrandom().Next(100300));
继续;
}
捕获(异常)
{
//仅适用于示例代码:只需跟踪异常。
ServiceEventSource.Current.MessageEvent(exception.ToString());
}
}
}
本质上,在本例中,服务每100ms轮询一次ReliableQueue以获取消息。有没有办法在不进行轮询的情况下进行此操作?我们是否可以订阅事件或在消息成功添加到ReliableQueue时触发的事件?否,当前没有可用于ReliableQueue的事件。您必须oll用于新项目。我建议在您的服务中使用,或者只使用 使用Dispatcher服务可以编写一个方法,每当某个项在基础可靠队列中排队时,就会调用该方法 例如:
public override async Task OnItemDispatchedAsync(
ITransaction transaction,
int value,
CancellationToken cancellationToken)
{
// Do something with the value that has been dequeued
}
可靠调度程序和调度程序服务都可以通过使用,GitHub上有完整的文档和示例,可以帮助您开始:
- 使用示例
- 使用示例