重构一个异步方法

3

我有一个项目,其中有一个动作目录。在每个动作的核心中,可能会有一个或多个网络调用。因此,核心方法看起来像以下内容:

public async Task<Result> evaluate(){
//some setup chunk
        try
        {
            responsefromUri = await requestManager.Post(resourceUri, "");
        }
            // The non-retryable exception will directly trickle up.
        catch (RetryableException exception)
        {
            return BuildFailedCheckResult(
                StatusCode.Abandoned,
                Check1 + " abandoned. Failed to read the response for resource: " + resourceUri + " with exception: " + exception.Message);
        }

        if (string.IsNullOrEmpty(responsefromUri))
        {
            return BuildFailedCheckResult(
                StatusCode.Failed,
                Check1 + " failed. Empty response for resource: " + resourceUri);
        }

        try
        {
            responseJson = JObject.Parse(responsefromUri);
        }
        catch (JsonReaderException e)
        {
            throw new InvalidOperationException(Check1 + " check failed parsing resource: " + resourceUri, e);
        }
// use responseJson to get data and process further
}

对于每个网络调用,都有这个块。我希望将其提取出来。现在,我无法这样做,因为存在一个await,如果要提取它,我需要一个异步方法;但是要返回失败的检查结果,我需要一个out变量,而在异步方法中不允许使用。重构此代码的正确方法是什么?当存在多个网络调用时,该方法会变得非常冗长。

2个回答

1

只需将您的“进一步处理”打包到一个Func中,例如:

public async Task<Result> evaluate(Uri resourceUri, Func<JObject, Result> action)
{
    string responsefromUri;

    try
    {
        responsefromUri = await requestManager.Post(resourceUri, "");
    }
        // The non-retryable exception will directly trickle up.
    catch (RetryableException exception)
    {
        return BuildFailedCheckResult(
            StatusCode.Abandoned,
            Check1 + " abandoned. Failed to read the response for resource: " + resourceUri + " with exception: " + exception.Message);
    }

    if (string.IsNullOrEmpty(responsefromUri))
    {
        return BuildFailedCheckResult(
            StatusCode.Failed,
            Check1 + " failed. Empty response for resource: " + resourceUri);
    }

    JObject responseJson;
    try
    {
        responseJson = JObject.Parse(responsefromUri);
    }
    catch (JsonReaderException e)
    {
        throw new InvalidOperationException(Check1 + " check failed parsing resource: " + resourceUri, e);
    }

    return action(responseJson);
}

使用示例:

// Example Usage
public Task<Result> DoStuff() 
{
    Uri uri = new Uri("http://localhost");

    return evaluate(uri, jobject => {
        return new Result(jobject["result"]);
    });
}

0
你可以将代码块重构为一个单独的私有方法,返回一个Task,并添加一个JsonResult类,其中包含“happy-path”结果。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接