簡體   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