【发布时间】:2017-01-29 07:29:50
【问题描述】:
我认为RunAsync 方法将CancellationToken 作为参数,这很棒。 不幸的是,根据我的观察,我从来没有被取消过。
当然,取消 RunAsync 方法 调用 OnCloseAsync 有点多余。 我仍然想知道取消何时(如果)实际发生。
我是否应该编写一些额外的代码来在我的客户端中提供一个有效的 Stop() 方法?我更希望 RunAsync 中的 cancelToken 实际上会被取消;-)
我的 Service Fabric 服务代码:
/// <summary>
/// This is the main entry point for your service instance.
/// </summary>
/// <param name="cancellationToken">Canceled when Service Fabric needs to shut down this service instance.</param>
protected override async Task RunAsync(CancellationToken cancellationToken)
{
// TODO: Replace the following sample code with your own logic
// or remove this RunAsync override if it's not needed in your service.
long iterations = 0;
while (!cancellationToken.IsCancellationRequested)
{
// I commented this out because I want my client to handle the cancellation
// event gracefully without throwing an OperationCanceled exception.
//cancellationToken.ThrowIfCancellationRequested();
// I never found these messages in any logs. Nor in the diagnostics events window in Visual Studio.
ServiceEventSource.Current.ServiceMessage(this, "Working-{0}", ++iterations);
await _client.Start(cancellationToken);
await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken);
}
}
我的示例客户端实现:
public class Client
{
private static readonly Logger _logger = LogManager.GetCurrentClassLogger();
public async Task Start(CancellationToken cancellationToken = default(CancellationToken))
{
while (!cancellationToken.IsCancellationRequested)
{
_logger.Info("Saying hello from Main Operation.");
await Task.Delay(3000, cancellationToken);
}
_logger.Info("Cancellation requested. Shutting down MainOperation().");
}
public void Stop()
{
_logger.Info("Stop requested. But I have no means to stop. Not implemented.");
}
}
【问题讨论】:
-
同样,一种方法是在完成后以编程方式删除服务,使用 DeleteServiceAsync 您也可以使用 CreateServiceAsync 重新创建它。
-
当然。但我不想在 Service Fabric 之外运行任何代码。还调用了 OnCloseAsync,这很好。我可以使用它。我仍然想知道 RunAsync 的 cancelToken 何时被设置为“cancel”。
-
您可以从其他服务调用它。它在服务停止、升级、从辅助副本移动到主副本和/或在集群中重新定位时调用。
-
你如何从另一个服务中调用这个取消?有人可以帮助了解取消令牌在那种情况下的用法吗?
-
我自己没有尝试过,但您可以使用例如Service Fabric Manager 或PowerShell。如果您忽略 RunAsync 中的取消令牌,则服务结构服务无法正常关闭