2013-02-27 45 views
7

我有以下的代碼,它似乎經過的毫秒是不準確的:測量C#/異步數據訪問使用秒錶類

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(); 
    } 

這是否看起來是正確的還是我失去了一些東西非常明顯?

+1

它看起來OK我。爲什麼你認爲它不準確?僅供參考,使用這種技術無法精確測量非常短的時間;檢查'Stopwatch.Frequency'字段。 – 2013-02-28 00:47:35

+0

對我也很好。只是做了一個小測試(https://dotnetfiddle.net/wLzfor),看看async是否因爲某種原因擺弄了秒錶,但事實並非如此。 – Jcl 2015-08-26 06:24:08

+0

(甚至使用'ConfigureAwait(false)'工作) – Jcl 2015-08-26 07:41:06

回答

0

這看起來對我完全沒問題。

一個潛在的錯誤是,如果Repository.GetAll方法不是異步,希望它有像這樣的簽名:

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

我不認爲它會編譯沒有異步方法簽名 – Jcl 2015-08-26 06:14:24