[英]Factory pattern in Parallel, returning a new instance of a class from a static method
I am writing a wrapper for a dll. 我正在为dll编写包装器。 I'm using a factory pattern with a manager class for configuring purposes. 我正在使用带有管理器类的工厂模式进行配置。
public sealed class Manager {
private static readonly factory = new Factory();
//prevents the default instance from being instantiated
private Manager(){}
public static IFoo GetMyIFoo(IParam param) {
return factory.GetMyIFoo(param);
}
}
Then my factory handles the instantiating configuration: 然后,我的工厂处理实例化配置:
public class Factory {
public IFoo GetMyIFoo(IParam param) {
IFoo foo = new Foo(param);
foo.SetConfiguration(this.Configuration, this);
return foo;
}
}
In my parallel foreach: 在我的并行foreach中:
Parallel.ForEach(fooThings, (fooThing, state) => {
using(var foo = Manager.GetMyIFoo(fooThing)) {
foo.MyDllMethods(); //throws an error in parallel
}
});
My code works fine in a vanilla foreach
, but I'm getting AccessViolationException when ran under Parallel.ForEach
: 我的代码在普通的foreach
运行良好,但是在Parallel.ForEach
下运行时出现了AccessViolationException:
Attempted to read or write protected memory. 尝试读取或写入受保护的内存。 This is often an indication that other memory is corrupt. 这通常表明其他内存已损坏。
If I step through the error with F10
, I get the best clue is from the DLL itself: 如果我逐步解决了F10
的错误,则最好的线索是来自DLL本身:
You can operate on an instance only in the thread which created it. 您只能在创建实例的线程中对其进行操作。
What is happening? 怎么了?
As I stated in my comment, foo.SetConfiguration(this.Configuration, this); 正如我在评论中所述,foo.SetConfiguration(this.Configuration,this); I think 'this' is the problem. 我认为这是问题所在。 You are sharing an instance created by one thread with another thread since you have a static variable in the manager 您正在共享一个线程与另一个线程创建的实例,因为您在管理器中有一个静态变量
public sealed class Manager
{
//prevents the default instance from being instantiated
private Manager() { }
public static IFoo GetMyIFoo(IParam param)
{
Factory factory = new Factory();
return factory.GetMyIFoo(param);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.