mar*_*abe -1 c# linq async-await
我在Northwind DB上使用异步LINQ有点麻烦,但是遇到了问题Task.WaitAll(task1, task2)。以下是我从中调用的方法static void Main(string[] args)。
public static void PerformDatabaseOperations()
{
using (var ne = new NORTHWNDEntities())
{
try
{
var aup = ne.Products.AverageAsync(p => p.UnitPrice)
.ContinueWith(t => Console.WriteLine($"Average unit price is {t.Result}"));
var ao = ne.Orders.GroupBy(o => o.OrderDate).AverageAsync(group => (double)group.Count())
.ContinueWith(t => Console.WriteLine($"Average orders per day is {t.Result}"));
Task.WaitAll(aup, ao);
}
catch (AggregateException ex)
{
Console.WriteLine(ex.ToString());
}
}
}
Run Code Online (Sandbox Code Playgroud)
当我运行它时会抛出AggregateException:
System.AggregateException: One or more errors occurred. --->
System.AggregateException: One or more errors occurred. --->
System.NotSupportedException: A second operation started on this context before a previous asynchronous operation completed. Use 'await' to ensure that any asynchronous operations have completed before calling another method on this context. Any instance members are not guaranteed to be thread safe.
Run Code Online (Sandbox Code Playgroud)
这种方法有什么我想念的吗?感谢您的任何提示。
DbContext不是线程安全的-您不能在2个线程中使用同一实例。
根据异常的建议,只需将代码更改为:
public static async Task PerformDatabaseOperations()
{
using (var ne = new NORTHWNDEntities())
{
try
{
var t = await ne.Products.AverageAsync(p => p.UnitPrice);
Console.WriteLine($"Average unit price is {t}");
var ao = await ne.Orders.GroupBy(o => o.OrderDate).AverageAsync(group => (double)group.Count());
Console.WriteLine($"Average orders per day is {ao}");
}
catch (AggregateException ex)
{
Console.WriteLine(ex.ToString());
}
}
}
Run Code Online (Sandbox Code Playgroud)
注意async Task方法定义。
如果您确实想同时执行两个查询,则每个任务都需要自己的DbContext实例。
| 归档时间: |
|
| 查看次数: |
69 次 |
| 最近记录: |