根据文档示例,代理的创建方式如下:
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/