开发者

Multi-Threaded SubQueries using Entity Framework throws errors

I have been trying to update the performance of my code in regards to database queries. The problem I am currently running into is that I cant seem to find a way to get a new context for each subQuery.

Using the below simplified code will inconsitantly generate a "The underlying provider failed on Open."

using (var context = getNewContextObject())
{
开发者_Python百科    var result = new SomeResultObject();
    var parentQuery = context.SomeTable.Where(x => x.Name = "asdf");

    Parallel.Invoke(() =>
        {
            result.count1 = parentQuery.Where(x => x.Amount >= 100 & x.Amount < 2000).Count();
        }, () =>
        {
            result.count2 = parentQuery.Where(x => x.Amount < 100).Count();
        }
        , () =>
        {
            result.count3 = parentQuery.Where(x => x.Amount >= 2000).Count();
        }
    );

}

The only way around this so far seems to be to rebuild the entire query for each subQuery with a new context. Is there any way to avoid building each query from the bottom up with a new Context? Can I instead just attach each subquery query to a new context? I am looking for something like the below.

    Parallel.Invoke(() =>
        {
            var subQuery = parentQuery.Where(x => x.Amount >= 100 & x.Amount < 2000).Count();
            subQuery.Context = getNewContextObject();
            result.count1 = subQuery.Count();

        }, () =>
        {
            var subQuery = parentQuery.Where(x => x.Amount < 100).Count();
            subQuery.Context = getNewContextObject();
            result.count2 = subQuery.Count();
        }
        , () =>
        {
            var subQuery = parentQuery.Where(x => x.Amount >= 2000).Count();
            subQuery.Context = getNewContextObject();
            result.count3 = subQuery.Count();
        }
    );

}


I'm not sure how this exactly relates to your problem but none of EF features are thread safe so I expect that running multiple queries on the same context instance in parallel can blow up for any reason. For example they access the same connection property in the context but threads don't know about each other so they can close the connection to other thread or replace the instance with other connection instance (you can try to open the connection manually before you run parallel threads and close it once all threads are done but it doesn't have to be the only problem).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜