2016-02-24 101 views
3

因此,我開始將我的nHibernate網站轉換爲使用Dapper的概念證明。出現MVC 6異步操作

是我的工作

我的操作方法是正確的,現在的工作:

public IActionResult About() 
{ 
    ViewData["Message"] = "Your application description page."; 

    var invoice = invoiceRepo.GetInvoiceAsync(19992031); 
    var allInvoices = invoiceRepo.GetAllInvoicesAsync(); 

    var model = new Models.AboutModel 
    { 
     Invoice = invoice.Result, 
     AllInvoices = allInvoices.Result 
    }; 

    return View(model); 
} 

但後來我意識到/牢記,爲了它是異步的,我需要有Task上行動,像這樣:

public Task<IActionResult> About() 
{ 
    ViewData["Message"] = "Your application description page."; 

    var invoice = invoiceRepo.GetInvoiceAsync(19992031); 
    var allInvoices = invoiceRepo.GetAllInvoicesAsync(); 

    var model = new Models.AboutModel 
    { 
     Invoice = invoice.Result, 
     AllInvoices = allInvoices.Result 
    }; 

    return View(model); 
} 

但是,只要我這樣做,它告訴我,我需要等待的東西。在我見過的所有例子中,它只是顯示了這樣的內容:

var result = await repo.Get(param); 

但是我已經在我的回購中「等待」了。

public async Task<Invoice> GetInvoiceAsync(int invoiceId) 
{ 
    const string query = "select InvoiceId, Name [InvoiceName] from dbo.Invoice where InvoiceId = @invoiceId"; 

    using (var conn = GetConnection()) 
    { 
     var dp = new DynamicParameters(); 
     dp.Add("@invoiceId", invoiceId); 

     await conn.OpenAsync(); 
     var invoiceResult = await conn.QueryAsync<Invoice>(query, dp, null, 30, CommandType.Text); 
     var invoice = invoiceResult.SingleOrDefault(); 

     return invoice; 
    } 
} 

public async Task<List<Invoice>> GetAllInvoicesAsync() 
{ 
    const string query = "select InvoiceId, Name [InvoiceName] from dbo.Invoice where SalesPeriodId >= 17"; 

    using (var conn = GetConnection()) 
    { 
     await conn.OpenAsync(); 
     var invoiceResult = await conn.QueryAsync<Invoice>(query, null, null, 30, CommandType.Text); 
     var invoices = invoiceResult.Take(1000).ToList(); 

     return invoices; 
    } 
} 

所以我切換到異步整點是能夠返回時,兩者都做我的電話的異步,然後合併在一起的結果。

如何更改我的控制器操作以異步執行此操作,同時擁有Task<IActionResult>?像這樣:

public Task<IActionResult>About() {} 

更新:這是正確的嗎?

public async Task<IActionResult> About() 
{ 
    ViewData["Message"] = "Your application description page."; 

    var invoice = invoiceRepo.GetInvoiceAsync(19992031); 
    var allInvoices = invoiceRepo.GetAllInvoicesAsync(); 

    var model = new Models.AboutModel 
    { 
     Invoice = await invoice, 
     AllInvoices = await allInvoices 
    }; 

    return View(model); 
} 

這是否會同時執行兩個回購調用(並行)?

+2

幾乎可以確定你想要'VAR模型=新Models.AboutModel { 發票=伺機發票, AllInvoices =等待allInvoices };' –

+0

@ganders:就在雞蛋裏挑骨頭 - 它可能會更好,有'變種發票=等待invoiceRepo.GetInvoiceAsync(19992031);'和allInvoices'類似,因爲這種方式稱爲'invoice'的變量實際上是指發票,而不是最終導致發票的任務。 –

回答

1

您也需要等待您的控制器。經驗法則:永遠不要說.Result,而是說await

您還應該聲明您的操作方法爲public async

更新:這將是異步調用您的存儲庫的正確方法。數據庫調用應該並行進行,因爲兩個任務都是在等待任何事情之前啓動的。您可以隨時通過在DB方法的開始和結束處放置調試日誌並看到您獲得「start 1 start 2 end 1 end 2」或類似的內容而不是「start 1 end 1 start 2 end 2」來查看此內容您的查詢相當慢。

+0

謝謝,請參閱上面的「更新」進行確認... – ganders