因此,我開始將我的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);
}
這是否會同時執行兩個回購調用(並行)?
幾乎可以確定你想要'VAR模型=新Models.AboutModel { 發票=伺機發票, AllInvoices =等待allInvoices };' –
@ganders:就在雞蛋裏挑骨頭 - 它可能會更好,有'變種發票=等待invoiceRepo.GetInvoiceAsync(19992031);'和allInvoices'類似,因爲這種方式稱爲'invoice'的變量實際上是指發票,而不是最終導致發票的任務。 –