[英]ControllerContext throwing error in Parallel.ForEach in mvc c#
I have function which return string and it has parameter of ControllerContext and this is throwing error 我有返回字符串的函数,并且它具有ControllerContext的参数,这会引发错误
Here is code 这是代码
var cContext = ControllerContext;
Parallel.ForEach(listInvHeaderIDs, x =>
{
body = new myClass().myFunctionReturnString(cContext);
}
Can we use ControllerContext in Parallel.Foreach if not than what to use 我们可以在Parallel.Foreach中使用ControllerContext吗?
You can probably try this overload of the Parallel.ForEach
: 您可能可以尝试Parallel.ForEach
此重载:
public static ParallelLoopResult ForEach<TSource, TLocal>(IEnumerable<TSource> source,
Func<TLocal> localInit, Func<TSource, ParallelLoopState, TLocal, TLocal> body,
Action<TLocal> localFinally)
Executes a
foreach
operation with thread-local data on anIEnumerable
in which iterations may run in parallel, and the state of the loop can be monitored and manipulated. 使用IEnumerable
上的线程本地数据执行foreach
操作,其中迭代可以并行运行,并且可以监视和操纵循环的状态。
An example of usage: 用法示例:
UDPATE I've updated the example, should be ok now. UDPATE我已经更新了示例,现在应该可以了。
Parallel.ForEach(listInvHeaderIDs, () => {return cContext; },
(listId, loopInfo, ctrlContext) =>
{
body = new myClass().myFunctionReturnString(ctrlContext);
return ctrlContext;
},
(ctrlContext) => { /*access controller context if needed...*/} );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.