在.net核心中调用外部服务时如何等待异步方法完成?

ank*_*kur 0 c# async-await asp.net-core

我已经看到了一些关于异步等待完成的现有问题,但对我来说,没有一个解决方案可行.

我使用C#包装器连接销售人员https://github.com/developerforce/Force.com-Toolkit-for-NET/

在下面的方法中,我想等待UsernamePasswordAsync方法完成执行,以便我可以从auth对象获取值.

public async Task<Token> GetTokenForSalesForce()
{
    Token token = null;
    try
    {
        var auth = new AuthenticationClient();
         await auth.UsernamePasswordAsync(configuration.Value.ClientId, configuration.Value.ClientSecert,
                                         configuration.Value.SFUsername, configuration.Value.SFPassword,
                                         configuration.Value.SFBaseUrl);
        if (!string.IsNullOrEmpty(auth.AccessToken) && !string.IsNullOrEmpty(auth.InstanceUrl))
        {
            token = new Token
            {
                BearerToken = auth.AccessToken,
                InstanceURL = auth.InstanceUrl,
                ApiVersion = auth.ApiVersion
            };
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
    return token;
}

public async Task<List<SFDashboardResponse>> GetOrderCountFromSalesForce(Token token)
{
    List<SFDashboardResponse> sFDashboardResponses = new List<SFDashboardResponse>();
    try
    {
        var client = new ForceClient(token.InstanceURL, token.BearerToken, token.ApiVersion);
        var response = await client.QueryAsync<SFDashboardResponse>("SELECT something ");
        var records = response.Records;
    }
    catch(Exception e)
    {

    }
    return sFDashboardResponses;
}
Run Code Online (Sandbox Code Playgroud)

图书馆的签名是

public async Task WebServerAsync(string clientId, string clientSecret, string redirectUri, string code, string tokenRequestEndpointUrl)
{
}
Run Code Online (Sandbox Code Playgroud)

问题是当方法等待等待首先执行时,另一个线程执行orignal调用者的另一部分.

我从这里叫它

public IActionResult post()
{
    var authtoken = _salesForceService.GetTokenForSalesForce();
    var response = _salesForceService.GetOrderCountFromSalesForce(authtoken.Result);
    DashboardModel dashboardModel = null;
    if (authtoken.Status == TaskStatus.RanToCompletion)
    {
       fill the object
    }

     return Ok(dashboardModel);
 }
Run Code Online (Sandbox Code Playgroud)

Raj*_*gaj 5

您可以IActionResult使用以下任务包装Taskawait执行.

public async Task<IActionResult> post()
{
    var authtoken = await _salesForceService.GetTokenForSalesForce();
    var response = await _salesForceService.GetOrderCountFromSalesForce(authtoken);

    DashboardModel dashboardModel = //fill the object

    return Ok(dashboardModel);
}
Run Code Online (Sandbox Code Playgroud)

根据我的理解,至少这是你要求的,如果它的另一个问题让我知道.

编辑1:

这只是我的建议/意见.

就个人而言,我真的不喜欢将代码包装在try-catch中,这样代码就很难阅读和维护.你真的应该考虑在一个地方集中异常处理,你可以有一个基本控制器或只有这样的中间件:

public class ErrorHandlingMiddleware
{
    private readonly RequestDelegate _next;

    public ErrorHandlingMiddleware(RequestDelegate next)
    {
        this._next = next;
    }

    public async Task Invoke(HttpContext context, ILogger logger)
    {
        try
        {
            await _next(context);
        }
        catch (Exception ex)
        { 
            await HandleExceptionAsync(context, ex, logger);
        }
    }

    private static Task HandleExceptionAsync(HttpContext context, Exception exception, ILogger logger) 
    {
        logger.Log(exception);
        //do something
        return context.Response.WriteAsync(... something ...); //Maybe some JSON message or something
    }
}
Run Code Online (Sandbox Code Playgroud)

您只需在Configure下面的方法中将其注册为中间件:

app.UseMiddleware<ErrorHandlingMiddleware>();
Run Code Online (Sandbox Code Playgroud)