簡體   English   中英

任務WaitAll在數據庫任務的C#中無法正常工作

[英]Task WaitAll not working properlyin C# for DB task

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

當我運行它時會拋出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.

這種方法有什么我想念的嗎? 感謝您的任何提示。

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

注意方法定義中的async Task

如果您確實想同時執行兩個查詢,則每個任務都需要自己的DbContext實例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM