我发现
当然取消RunAsync方法并调用OnCloseAsync可能有点多余。但我仍然想知道(如果)取消实际上何时发生。
我需要编写一些额外的代码来提供工作中的Stop()方法吗?我更希望在RunAsync中的cancellationToken实际上会被取消;-)
我的Service Fabric Service代码:
RunAsync
方法需要一个CancellationToken
作为参数,这很好。不幸的是,根据我的观察,它从未被取消。当然取消RunAsync方法并调用OnCloseAsync可能有点多余。但我仍然想知道(如果)取消实际上何时发生。
我需要编写一些额外的代码来提供工作中的Stop()方法吗?我更希望在RunAsync中的cancellationToken实际上会被取消;-)
我的Service Fabric Service代码:
/// <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.");
}
}