【发布时间】:2018-04-11 00:40:34
【问题描述】:
更新:
问题已解决。这两段代码实际上都有效。一个潜在的问题导致失败。
我不是线程专家,但这是我的场景。
我有两个 WCF 服务(ServiceA 和 ServiceB)
ServiceA必须
- 每秒或配置的间隔轮询
ServiceB, - 对于某种状态,
- 阻塞直到
ServiceB恢复所需状态 - ServiceA 方法然后进行下一个操作
专注于Service A的实现以实现需求,并假设我使用Service B的生成服务引用,干净地处理和关闭,定义接口:
public class ServiceA : IServiceA
{
public ResultObject ServiceAMethod()
{
var serviceBClient = new ServiceBReference.ServiceBClient();
//do sometthing
//call ServiceB every 1second until the status changes or a WCF timeout ends the process
return new ResultObject{/*set whatever properties need to be set*/}
}
}
我已经尝试过并且没有阻止:
尝试 1
public class ServiceA : IServiceA
{
public ResultObject ServiceAMethod()
{
var serviceBClient = new ServiceBReference.ServiceBClient();
//do sometthing
//call ServiceB every 1second until the status changes or a WCF timeout ends the process
var cancellationTokenSource = new CancellationTokenSource();
var token = cancellationTokenSource.Token;
SomeStatusEnum status;
int pollingInterval = 1000;
var listener = Task.Factory.StartNew(() =>
{
status = serviceBClient.GetStatus();
while (status != SomeStatusEnum.Approved)
{
Thread.Sleep(pollingInterval);
if (token.IsCancellationRequested)
break;
status = serviceBClient.GetStatus();
}
}, token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
return new ResultObject{/*set whatever properties need to be set determined by status*/}
}
}
}
尝试 2
public class ServiceA : IServiceA
{
public ResultObject ServiceAMethod()
{
var serviceBClient = new ServiceBReference.ServiceBClient();
//do sometthing
//call ServiceB every 1second until the status changes or a WCF timeout ends the process
SomeStatusEnum status;
int pollingInterval = 1000;
status = serviceBClient.GetStatus();
while (status == SomeStatusEnum.Approved)
{
status = serviceBClient.GetStatus();;
if (status != SomeStatusEnum.Approved)
{
break;
}
Thread.Sleep(pollingInterval);
}
return new ResultObject{/*set whatever properties need to be set determined by status*/}
}
}
在这两种情况下,状态都不会设置为预期值。我可能做错了什么?是否存在与 WCF 应用程序相关的可能导致此问题的行为?
我的来源:
【问题讨论】:
-
为什么对 ServiceB 的调用不能是阻塞(同步)调用。无论如何,您需要让 ServiceA 等到结果出现。是 ServiceB PerInstance、PerCall 还是 Singleton - 在 ServiceB 方法调用中放置一些日志以查看返回的状态。
-
如果它是同步的,@PrateekShrivastava 怎么做?
-
对 ServiceB 的调用是同步的。 GetStatus() 将被阻止,直到返回正确的状态。所以实际上 ServiceA 正在等待来自 ServiceB 的响应。
-
问题已解决。这两段代码实际上都有效。