繁体   English   中英

在另一个WCF服务内的阻塞调用中轮询WCF服务方法

[英]Polling a WCF service method in a blocking call within a another WCF service

更新:

该问题已解决。 这两段代码都可以正常工作。 一个潜在的问题正在导致失败。


我不是线程专家,但这是我的情况。

我有两个WCF服务( ServiceAServiceB

ServiceA必须

  1. 每隔一秒钟或配置的时间间隔轮询ServiceB
  2. 在某种状态下
  3. 阻塞,直到ServiceB恢复所需的状态
  4. 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应用程序相关联的可能导致此问题的行为?

我的资料

  1. 我应该始终使用Task.Delay而不是Thread.Sleep吗?
  2. WCF线程睡眠
  3. C#错误System.NullReferenceException
  4. 每x分钟调用一次方法
  5. 什么时候使用Task.Delay,什么时候使用Thread.Sleep?

这两段代码都可以正常工作。

可以删除问题,但选择留作参考,因为它还包括可以帮助下一个人的参考。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM