【问题标题】:Measuring C# / Async Data Access Using StopWatch Class使用 StopWatch 类测量 C#/异步数据访问
【发布时间】:2013-02-14 00:21:36
【问题描述】:

我有以下代码,但经过的毫秒数似乎不准确:

    public async Task<ActionResult> Index()
    {
        try
        {
            var connString = RoleEnvironment.IsEmulated
                                 ? ConfigurationManager.ConnectionStrings["Poc"].ConnectionString
                                 : ConfigurationManager.ConnectionStrings["PocVm"].ConnectionString;

            var repository = new AccountRepository(connString);
            var stopWatch = new Stopwatch();
            stopWatch.Start();

            var accounts = await repository.GetAll();

            stopWatch.Stop();
            ViewBag.Accounts = accounts;
            ViewBag.VmStatus = stopWatch.ElapsedMilliseconds;
        }
        catch (Exception e)
        {
            blah blah blah...
        }


        return View();
    }

这看起来是正确的还是我错过了一些非常明显的东西?

【问题讨论】:

  • 我觉得没问题。你为什么断定它不准确?仅供参考,使用这种技术无法准确测量非常短的时间;查看Stopwatch.Frequency 字段。
  • 我也觉得不错。刚刚做了一个小测试(dotnetfiddle.net/wLzfor),看看 async 是否出于某种原因摆弄了秒表,但事实并非如此。
  • (即使使用ConfigureAwait(false)也能工作)

标签: c# asynchronous


【解决方案1】:

这在我看来完全没问题。

如果 Repository.GetAll 方法不是异步的,可能会出现错误,希望它有这样的签名:

    public async Task<IEnumerable<Account>> GetAll();

【讨论】:

  • 我认为没有异步方法签名就无法编译
猜你喜欢
  • 2012-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-15
  • 1970-01-01
相关资源
最近更新 更多