在C#异步方法中设置变量值

时间:2019-08-21 10:18:06

标签: c# asynchronous asp.net-core async-await

我有一个模型,可以在async方法中设置接收者,然后,如果电子邮件的类型为X,则需要从其他两个对象生成URL。但是,model.Url不会在分配接收者时被分配。我应该如何修复它才能同时工作?

private async Task GenerateUrl(Model model)
{
    var urlModel = GetUrlByOrganizationId(model.OrgId);
    var org = GetOrg(model.Id);
    model.Url = brand.Domain + org.Name;
    await Task.FromResult(model.Url);
}

private async Task<Email> GenerateEmail(User receiver, Guid brandId)
{
    var model = new Model()
    {
        title = "",
        Organization = organization,
        Url = string.Empty
    };

    try
    {
        await model.SetReceiverAsync(receiver, 0, model.Locale, model.Dialect);
        await this.GenerateUrl(model);
    }
    catch (Exception exc)
    {
        this.Log(LogLevels.Warning, exc.Message);
        return null;
    }


    // Send email
    var email = Sender.RenderModel(template, model);
    return email;
}

我想在model.Url行中使用var email = Sender.RenderModel(template, model);

1 个答案:

答案 0 :(得分:1)

目前尚不清楚为什么将GenerateUrl定义为async方法并返回Task的原因。如果仅设置模型的Url属性,则应按以下方式定义:

private void GenerateUrl(Model model)
{
    var urlModel = GetUrlByOrganizationId(model.OrgId);
    var org = GetOrg(model.Id);
    model.Url = brand.Domain + org.Name;
}

并在没有await的情况下呼叫:

this.GenerateUrl(model);

如果您打算从方法中返回URL,则返回类型应为stringTask<string>(尽管考虑到当前的实现,后者没有多大意义):

private async Task<string> GenerateUrl(Model model)
{
    var urlModel = GetUrlByOrganizationId(model.OrgId);
    var org = GetOrg(model.Id);
    model.Url = brand.Domain + org.Name;
    return Task.FromResult(model.Url);
}

private async string GenerateUrl(Model model)
{
    var urlModel = GetUrlByOrganizationId(model.OrgId);
    var org = GetOrg(model.Id);
    model.Url = brand.Domain + org.Name;
    return model.Url;
}