如何制作此通用函数的异步版本?

时间:2016-04-28 19:45:17

标签: c# .net wcf generics

我有一个WCF库,它在连接到特定的Web服务时抽象出如此多的垃圾工作,而且它工作得很好!但是,我想更新库以允许异步使用,但我遇到了一个包含两个特定泛型函数的障碍,我使用它修复了一些WCF问题和/或以通用形式处理审计:

此函数确保WCF请求具有从适配器类设置的三个特定标头,并以特定方式处理异常处理:

internal T PerformWCFServiceCall<TIn, T>(Func<TIn, T> wcfOperation, TIn ebsRequest) where TIn : class
{
    T retVal = default(T);

    try
    {
        // Set the EBS headers
        // It would be nice to constrain request as an instance of IEBSMessage but that's not a feature of the language :(
        (ebsRequest as IFunkyServiceMessage<funky_headerA, funky_headerB, funky_header>).EBS = this._ebsHeader;
        /*.. other code ..*/

        if (this.State != CommunicationState.Opened) { this.Open(); }

        retVal = (T) wcfOperation(ebsRequest);
    }
    catch (FaultException<ebsFault> ebsFaultEx)
    {
        // acknowledge the Faulted state and transition to Closed
        this.Abort();

        // handle or throw
        throw ebsFaultEx;
    }
    catch (FaultException faultEx)
    {
        // acknowledge the Faulted state and transition to Closed
        this.Abort();

        // handle or throw
        throw faultEx;
    }
    catch (Exception)
    {
        // acknowledge the Faulted state and transition to Closed
        this.Abort();

        // handle or throw
        throw;
    }
    return retVal;
}

此功能的用法如下:

public getTypeListResponse GetTypeList(getTypeListRequest request)
{
    return PerformServiceCall(
        (getTypeListRequest) =>
        {
            return base.getTypeList(request);
        },
        request);
}

但我希望它看起来像这样:

public async Task<getTypeListResponse> GetTypeList(getTypeListRequest request)
{
    return await PerformWCFServiceCall(
        async (getTypeListRequest) =>
        {
            return await base.getTypeListAsync(request).ConfigureAwait(false);
        },
        request).ConfigureAwait(false);
}

现在,将方法签名更改为:

是否正确
internal async Task<T> PerformWCFServiceCall<TIn, T>(Func<TIn, Task<T>> callToPerform, TIn ebsRequest) where TIn : class

这一行:

var result = await callToPerform(ebsRequest).ConfigureAwait(false);
retVal = (T) result;

我得到的一般信息是:&#34; Task<T>不包含GetAwaiter的定义,也没有扩展方法GetAwaiter接受{{1}类型的第一个参数可以找到。&#34;而且我不确定原因。

0 个答案:

没有答案