Update:
The issue has been resolved. Both pieces of code actually work. An underlying issue was causing failure.
I am not much of a threading expert but this is my scenario.
I have two WCF
services (ServiceA
and ServiceB
)
ServiceA
must
- poll
ServiceB
every second or configured interval, - for a certain status,
- blocking until
ServiceB
retuns the desired status - ServiceA method then proceeds to its next action
Focusing on the implementation of Service A
to achieve the requirement, and assuming I am using a generated service reference for Service B
, cleanly disposing and closing, with interfaces defined:
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*/}
}
}
What I have tried and does not block:
Attempt 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*/}
}
}
}
Attempt 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*/}
}
}
In both cases, status is never set to the expected value. What could I be doing wrong? Is there behavior associated with WCF applications that could be causing this?
My sources: