更新
此问题已得到解决。这两段代码实际上都有效。一个潜在的问题是导致失败。
我不是一个线程专家,但这是我的方案。
我有两个WCF
服务(ServiceA
和ServiceB
)
ServiceA
必须
ServiceB
,ServiceB
返回所需状态专注于实现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应用程序相关联的行为?
我的来源:
答案 0 :(得分:0)
这两段代码实际上都有效。
可以删除问题,但选择将其留作参考,因为它还包含可能有助于下一个人的参考。