重构异步方法

本文关键字:异步方法 重构 | 更新日期: 2023-09-27 18:30:33

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

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 变量。重构此代码的正确方法是什么?当有多个网络调用时,方法会变得非常冗长。

重构异步方法

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

您可以将代码块重构为在返回 Task 的单独私有方法中,并添加一个包含"快乐路径"结果的 JsonResult 类