重构异步方法

时间:2016-01-15 06:26:56

标签: c# asynchronous refactoring

我有一个项目,我们有一个各种行动目录。在每个操作的核心,可以有一个或多个网络呼叫。因此,核心方法如下所示:

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
}

每个网络呼叫都有这个块。我想解决这个问题。现在,我不能这样做,因为有一个等待并提取它我需要一个异步方法;但要返回失败的检查结果,我需要一个在异步方法中不允许的out变量。重构此代码的正确方法是什么?当有多个网络呼叫时,方法会变得非常冗长。

2 个答案:

答案 0 :(得分:1)

只需打包您的进一步处理&#39;进入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"]);
    });
}

答案 1 :(得分:0)

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