Parallel 中的工厂模式,从静态方法返回 class 的新实例

Factory pattern in Parallel, returning a new instance of a class from a static method

我正在为一个 dll 写一个包装器。我正在使用工厂模式和经理 class 进行配置。

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

然后我的工厂处理实例化配置:

public class Factory {
    public IFoo GetMyIFoo(IParam param) {
        IFoo foo = new Foo(param);
        foo.SetConfiguration(this.Configuration, this);
        return foo;
    }
}

在我的并行 foreach 中:

Parallel.ForEach(fooThings, (fooThing, state) => {
    using(var foo = Manager.GetMyIFoo(fooThing)) {
        foo.MyDllMethods(); //throws an error in parallel
    }
});

我的代码在 vanilla foreach 中运行良好,但是当 运行 在 Parallel.ForEach 下时我得到 AccessViolationException:

Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

如果我使用 F10 逐步解决错误,我从 DLL 本身得到最好的线索:

You can operate on an instance only in the thread which created it.

发生了什么事?

正如我在评论中所说,foo.SetConfiguration(this.Configuration, this);我认为 'this' 是问题所在。您正在与另一个线程共享一个线程创建的实例,因为您在管理器中有一个静态变量

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