使用StopWatch类测量C# / Async数据访问

7
我有下面的代码,但是似乎经过的毫秒数不准确:
    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();
    }

这看起来正确吗?还是我漏掉了什么非常明显的东西?


2
我认为它看起来没问题。你为什么得出它不准确的结论?顺便说一下,使用这种技术无法准确地测量非常短的时间间隔;请查看Stopwatch.Frequency字段。 - Stephen Cleary
我也觉得没问题。只是做了一个小测试(https://dotnetfiddle.net/wLzfor),看看异步是否因某种原因干扰了秒表,但它没有。 - Jcl
(即使使用 ConfigureAwait(false) 也可以工作) - Jcl
1个回答

0

我认为这看起来完全没问题。

一个潜在的错误可能是如果Repository.GetAll方法不是异步的,希望它的签名是这样的:

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

1
我认为如果没有异步方法签名,它不会编译。 - Jcl

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接