簡體   English   中英

如何用await包裝方法調用?

[英]How to wrap method calls with await?

所有對該服務的呼叫都應通過個人渠道進行。 因此,所有可以訪問服務器代理的方法都應如下所示:

public async Task<SDRLocation[]> FindLocationsAsync(string searchString)
    {
        ChannelFactory<IQueryService> channel = new ChannelFactory<IQueryService>("SomeServ_IQuery");
        channel.Open();
        SomeProxy = channel.CreateChannel();
        Location[] locationEntitiesFound = await SomeProxy.FindLocationsAsync(searchString);
        ((IChannel)SomeProxy ).Close();

        return locationEntitiesFound.Select(x => new SDRLocation(x)).ToArray();
    }

但是因為有很多類似此服務調用的方法,所以我嘗試避免代碼重復並創建此方法包裝器:

public TResult HandleServiceCall<TResult>(Func<IPlantOrgQueryService, TResult> serviceMethod)
    {
        ChannelFactory<IQueryService> channel = new ChannelFactory<IQueryService>("SomeServ_IQuery");
        channel.Open();
        IQueryService newProxy = channel.CreateChannel();
        TResult results = serviceMethod(newProxy);
        ((IChannel)newProxy).Close();

         return results;
    }

現在,我希望到處撥打這樣的電話:

public async Task<SDRLocation[]> FindLocationsAsync(string searchString)
    {
        Location[] locationEntitiesFound = await HandleServiceCall(x => x.FindLocationsAsync(searchString));

        return locationEntitiesFound.Select(x => new SDRLocation(x)).ToArray();
    }

但是我最終遇到錯誤“通信對象System.ServiceModel.Channels.ClientReliableDuplexSessionChannel,由於已中止而無法用於通信”。

不明白是什么問題,因為沒有HandleServiceCall的方法可以正常工作...

請幫助

TResult的類型將讓您知道出了什么問題。 這是Task<Location[]> 因此,您要在異步調用完成之前處理代理(通過Close )。

解決方法是像調用原始代碼一樣,在調用Close之前先await Task 這應該可以解決問題:

public async Task<TResult> HandleServiceCall<TResult>(Func<IPlantOrgQueryService, Task<TResult>> serviceMethod)
{
    ChannelFactory<IQueryService> channel = new ChannelFactory<IQueryService>("SomeServ_IQuery");
    channel.Open();
    IQueryService newProxy = channel.CreateChannel();
    TResult results = await serviceMethod(newProxy);
    ((IChannel)newProxy).Close();

     return results;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM