azure-service-fabric - 如何使用 CancellationToken 调用 Azure Service Fabric 远程代理?

标签 azure-service-fabric service-fabric-remoting

根据文档示例,代理的创建方式如下:

IMyService helloWorldClient = ServiceProxy.Create<IMyService>(new 
Uri("fabric:/MyApplication/MyHelloWorldService"));

string message = await helloWorldClient.HelloWorldAsync();

但如果我需要限制最大响应时间,我通常会创建 CancellationToken 并将其传递给调用。有没有办法将 token 传递给代理,以便它取消等待远程服务的结果?

最佳答案

您可以在 V2 堆栈中执行此操作,我还没有尝试过 V1 堆栈,但它也可能在那里工作。在方法签名中添加CancellationToken类型的参数:

void HelloWorldAsync(CancellationToken cancellationToken);

此 token 随后将通过代理传递给 ServicePartitionClient.InvokeWithRetryAsync 方法。

生成的代理方法将如下所示:

Task<string> IMyService.HelloWorldAsync(CancellationToken cancellationToken)
{
    IServiceRemotingRequestMessageBody serviceRemotingRequestMessageBody = base.CreateRequestMessageBodyV2("MyNamespace.IMyService", "HelloWorldAsync", 1);
    Task<IServiceRemotingResponseMessageBody> task = base.InvokeAsyncV2(
    1, -1, "HelloWorldAsync", serviceRemotingRequestMessageBody,
    cancellationToken);
    return base.ContinueWithResultV2<ServiceInfoResponse>(task);
}

如果没有 CancellationToken 参数,代理方法如下所示:

Task<string> IMyService.HelloWorldAsync()
{
    IServiceRemotingRequestMessageBody serviceRemotingRequestMessageBody = base.CreateRequestMessageBodyV2("MyNamespace.IMyService", "HelloWorldAsync", 1);
    Task<IServiceRemotingResponseMessageBody> task = base.InvokeAsyncV2(
    1, -1, "HelloWorldAsync", serviceRemotingRequestMessageBody,
    CancellationToken.None);
    return base.ContinueWithResultV2<ServiceInfoResponse>(task);
}

如果要检查生成的代理程序集,请在 EntryPoint 程序集或定义了服务接口(interface)的程序集中使用以下属性:

[assembly: CodeBuilder(EnableDebugging = true)]

关于azure-service-fabric - 如何使用 CancellationToken 调用 Azure Service Fabric 远程代理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51326280/

相关文章:

c# - Service-Fabric 绑定(bind)到多个端点

azure - 减少 Service Fabric 备份大小

azure - Service Fabric 服务中的多个通信监听器

c# - 即使为 Assembly 设置 MaxMessageSize 后,Fabric Message 仍然太大

.net-core - 意外降级? Nuget 包管理器不显示 Microsoft.ServiceFabric.Services.Remoting 的最新版本

azure-service-fabric - 使用 UnmonitoredAuto 进行非常快速的部署

azure-service-fabric - 如何指定本地开发人员的服务结构集群的创建位置?