【问题标题】:How can I do async await in the repository pattern?如何在存储库模式中执行异步等待?
【发布时间】:2016-09-22 10:27:07
【问题描述】:

我的代码是长时间运行的 i/o 绑定,非常适合 async/await 。我正在做存储库模式,无法弄清楚如何在控制器中等待,因为我在此代码上得到一个 对象不包含等待方法

 public class HomeController : Controller
     {
    private ImainRepository _helper = null;

    public HomeController()
    {
        this._helper = new MainRepository();
    }
   public async Task<string> Aboutt()
    {
       // Here I get the error
       object main = await _helper.Top_Five() ?? null;
        if(main != null)
        {
            return main.ToString();
        }
        else
        {
            return null;
        }
    }
 }

我正在实施的方法可以正常工作,如下所示。我从数据库中获取数据并以字符串格式返回。我想要的是找到一种方法来制作 object main = await _helper.Top_Five() ?? null; 等待,否则我会将异步与同步代码混合使用。任何建议都会很棒...

    public async Task<string> Top_Five()
    {
        try
        {

            using (NpgsqlConnection conn = new NpgsqlConnection("Config"))
            {
                conn.Open();
                string Results = null;
                NpgsqlCommand cmd = new NpgsqlCommand("select * from streams limit 15)t", conn);


                using (var reader = await cmd.ExecuteReaderAsync())
                {
                    while (reader.Read())
                    {

                        Results = reader.GetString(0);
                    }

                    return  Results;
                }
            }
        }
        catch(Exception e)
        {
            // Log it here
            return null;
        }

    }

【问题讨论】:

  • 您的项目配置为使用哪个版本的 .NET 框架?很确定它必须 >= 4.5
  • 是的,它实际上是 Asp.Net Core RC2
  • 我无法重现该错误。你能提供一个minimal reproducible example吗?

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


【解决方案1】:

这对你有用吗?

object main = (await _helper.Top_Five()) ?? null;

请注意额外的(),因为您需要等待该方法,然后检查null

【讨论】:

  • 我刚试过,但它仍然给出了那个错误
  • 括号无济于事,这就是编译器理解该表达式的方式。
  • @svick 不确定您使用的是什么,但这给了我很多错误。
【解决方案2】:

考虑到 Top_Five 返回nullstring,代码是不必要的:

object main = await _helper.Top_Five() ?? null;

相反,请执行以下操作:

var main = await _helper.Top_Five(); // the "awaiter" completes now
return main; // returns a string or null like in your example

【讨论】:

  • 那还是多余的。
【解决方案3】:

问题是在Task 方法上使用null 合并运算符。您需要以不同的方式处理它,请考虑以下事项:

public class HomeController : Controller
{
    private ImainRepository _helper = null;

    public HomeController()
    {
        this._helper = new MainRepository();
    }

    public async Task<string> Aboutt()
    {
        string main = await _helper.Top_Five();
        return main;
    }
}

请注意,当您返回 string 时,您只需要 await,因此将其声明为 string - 而不是 object

【讨论】:

    【解决方案4】:

    您的整个方法一无所获。 ?? null 将 null 替换为 null 并将其他任何内容替换为自身。这是你对结果的唯一转换,所以你可以写:

    public Task<string> Aboutt()
    {
            return _helper.Top_Five();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-30
      • 2022-11-20
      • 2016-12-07
      • 1970-01-01
      • 2022-09-30
      • 1970-01-01
      • 2015-01-09
      • 1970-01-01
      相关资源
      最近更新 更多