gpt4 book ai didi

c# - Linq 和 foreach 中的并行处理

转载 作者:太空狗 更新时间:2023-10-30 01:04:19 25 4
gpt4 key购买 nike

这是我的代码:

        int j;
WebShopEntities data = new WebShopEntities();
var db = data;
var list =
(from line in System.IO.File.ReadLines(MyHttpApplication.GetAppDataPath() + "677254_dp_articles.TXT").AsParallel()
where line.EndsWith(";") && !((line.StartsWith("prom_erp_partno")))
let parts = line.Split('\t')
select new WebShop.dp_articles
{
prom_erp_partno = parts[0],
prom_mfm_partno = parts[1],
prol_name = parts[2],
mfm_short_name = parts[3],
prom_prfm_id=int.TryParse(parts[4],out j)?int.Parse(parts[4]):0,
prol_lng_id=int.Parse(parts[5]),
prol_variant=parts[6]??null,
vpl=parts[7]??null,
status=parts[8],
gross_weight=Decimal.Parse('0'+parts[9].Replace('.',',')),
commodity_code=parts[10],
returnable = parts[11].Replace(';', ' ').Trim()

}).ToList();
Parallel.ForEach(list, item =>
{

if (!(from x in db.dp_articles.AsParallel() where x.prom_erp_partno == item.prom_erp_partno select x).Any())
{

db.dp_articles.Add(new dp_articles
{
prom_erp_partno = item.prom_erp_partno,
prom_mfm_partno = item.prom_mfm_partno,
prol_name = item.prol_name,
mfm_short_name = item.mfm_short_name,
prom_prfm_id = item.prom_prfm_id,
prol_lng_id = item.prol_lng_id,
prol_variant = item.prol_variant,
vpl = item.vpl,
status = item.status,
gross_weight = item.gross_weight,
commodity_code = item.commodity_code,
returnable = item.returnable

});
}
else
{

var itemU = db.dp_articles.Find(item.prom_erp_partno);
itemU.prom_mfm_partno = item.prom_mfm_partno;
itemU.prol_name = item.prol_name;
itemU.mfm_short_name = item.mfm_short_name;
itemU.prom_prfm_id = item.prom_prfm_id;
itemU.prol_lng_id = item.prol_lng_id;
itemU.prol_variant = item.prol_variant;
itemU.vpl = item.vpl;
itemU.status = item.status;
itemU.gross_weight = item.gross_weight;
itemU.commodity_code = item.commodity_code;
itemU.returnable = item.returnable;
}

db.SaveChanges();
});

我需要并行执行这些过程,但我没有任何关于在 C# 中并行处理的信息。在 Google 中快速搜索后,我发现了这些并行语法,但在我运行它之后出现了这个错误:

The context cannot be used while the model is being created. This exception may be thrown if the context is used inside the OnModelCreating method or if the same context instance is accessed by multiple threads concurrently. Note that instance members of DbContext and related classes are not guaranteed to be thread safe.

和堆栈跟踪:

[InvalidOperationException: The context cannot be used while the model is being created. This exception may be thrown if the context is used inside the OnModelCreating method or if the same context instance is accessed by multiple threads concurrently. Note that instance members of DbContext and related classes are not guaranteed to be thread safe.] System.Data.Entity.Internal.LazyInternalContext.InitializeContext() +797 System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) +18 System.Data.Entity.Internal.Linq.InternalSet1.Initialize() +53
System.Data.Entity.Internal.Linq.InternalSet
1.GetEnumerator() +15 System.Data.Entity.Infrastructure.DbQuery1.System.Collections.Generic.IEnumerable<TResult>.GetEnumerator() +53
System.Linq.Parallel.PartitionedDataSource
1.InitializePartitions(IEnumerable1 source, Int32 partitionCount, Boolean useStriping) +501
System.Linq.Parallel.PartitionedDataSource
1..ctor(IEnumerable1 source, Int32 partitionCount, Boolean useStriping) +92
System.Linq.Parallel.ExchangeUtilities.PartitionDataSource(IEnumerable
1 source, Int32 partitionCount, Boolean useStriping) +277 System.Linq.Parallel.ScanEnumerableQueryOperatorResults.GivePartitionedStream(IPartitionedStreamRecipient1 recipient) +92
System.Linq.Parallel.UnaryQueryOperatorResults.GivePartitionedStream(IPartitionedStreamRecipient
1 recipient) +578 System.Linq.Parallel.UnaryQueryOperatorResults.GivePartitionedStream(IPartitionedStreamRecipient1 recipient) +441
System.Linq.Parallel.QueryOperator
1.GetOpenedEnumerator(Nullable1 mergeOptions, Boolean suppressOrder, Boolean forEffect, QuerySettings querySettings) +386
System.Linq.Parallel.QueryOpeningEnumerator
1.OpenQuery() +218 System.Linq.Parallel.QueryOpeningEnumerator1.MoveNext() +32
System.Linq.Parallel.AnyAllSearchOperator
1.Aggregate() +64 System.Linq.ParallelEnumerable.Any(ParallelQuery1 source, Func2 predicate) +92 System.Linq.ParallelEnumerable.Any(ParallelQuery1 source) +126
WebShop.Models.<>c__DisplayClass4f.<ArticlesParser>b__4b(dp_articles item) in c:\Users\Ahmad\Documents\Visual Studio 2013\Projects\WebShop\WebShop\Models\Ftp.cs:369
System.Threading.Tasks.<>c__DisplayClass2d
2.b__23(Int32 i) +63 System.Threading.Tasks.<>c__DisplayClassf1.<ForWorker>b__c() +910
System.Threading.Tasks.Task.InnerInvoke() +72
System.Threading.Tasks.Task.InnerInvokeWithArg(Task childTask) +17
System.Threading.Tasks.<>c__DisplayClass11.<ExecuteSelfReplicating>b__10(Object param0) +198
[AggregateException: One or more errors occurred.]
System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions) +3834425
System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken) +10919077
System.Threading.Tasks.Task.Wait() +10
System.Threading.Tasks.Parallel.ForWorker(Int32 fromInclusive, Int32 toExclusive, ParallelOptions parallelOptions, Action
1 body, Action2 bodyWithState, Func4 bodyWithLocal, Func1 localInit, Action1 localFinally) +925 System.Threading.Tasks.Parallel.ForEachWorker(IList1 list, ParallelOptions parallelOptions, Action1 body, Action2 bodyWithState, Action3 bodyWithStateAndIndex, Func4 bodyWithStateAndLocal, Func5 bodyWithEverything, Func1 localInit, Action1 localFinally) +223 System.Threading.Tasks.Parallel.ForEachWorker(IEnumerable1 source, ParallelOptions parallelOptions, Action1 body, Action2 bodyWithState, Action3 bodyWithStateAndIndex, Func4 bodyWithStateAndLocal, Func5 bodyWithEverything, Func1 localInit, Action1 localFinally) +10893169 System.Threading.Tasks.Parallel.ForEach(IEnumerable1 source, Action1 body) +110 WebShop.Models.Ftp.ArticlesParser() in c:\Users\Ahmad\Documents\Visual Studio 2013\Projects\WebShop\WebShop\Models\Ftp.cs:366 webshop.Controllers.HomeController.Index() in c:\Users\Ahmad\Documents\Visual Studio 2013\Projects\WebShop\WebShop\Controllers\HomeController.cs:46 lambda_method(Closure , ControllerBase , Object[] ) +62 System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14 System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 parameters) +156
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary
2 parameters) +27 System.Web.Mvc.Async.AsyncControllerActionInvoker.b__36(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +22 System.Web.Mvc.Async.WrappedAsyncResult2.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase
1.End() +49 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +32 System.Web.Mvc.Async.AsyncInvocationWithFilters.b__3c() +50 System.Web.Mvc.Async.<>c__DisplayClass45.b__3e() +225 System.Web.Mvc.Async.<>c__DisplayClass30.b__2f(IAsyncResult asyncResult) +10 System.Web.Mvc.Async.WrappedAsyncResult1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase
1.End() +49 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +34 System.Web.Mvc.Async.<>c__DisplayClass28.b__19() +26 System.Web.Mvc.Async.<>c__DisplayClass1e.b__1b(IAsyncResult asyncResult) +100 System.Web.Mvc.Async.WrappedAsyncResult1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase
1.End() +49 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27 System.Web.Mvc.Controller.b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +13 System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +36
System.Web.Mvc.Async.WrappedAsyncResultBase
1.End() +54 System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +39 System.Web.Mvc.Controller.b__15(IAsyncResult asyncResult, Controller controller) +12 System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +28
System.Web.Mvc.Async.WrappedAsyncResultBase
1.End() +54 System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +29 System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10 System.Web.Mvc.MvcHandler.b__4(IAsyncResult asyncResult, ProcessRequestState innerState) +21 System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +36
System.Web.Mvc.Async.WrappedAsyncResultBase
1.End() +54 System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +31 System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9690172 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

此代码解析一个文本文件并尝试将其放入数据库或更新它(如果存在)。

最佳答案

简而言之,您正在从多个线程并发使用 EF。那是不允许的。扫描您的所有代码并确保没有一个地方在多个线程中使用相同的 EF ObjectContext(等)。

或许,您应该为每个线程或每个工作单元创建一个上下文。

关于c# - Linq 和 foreach 中的并行处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23887104/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com