简体   繁体   中英

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

I am writing a wrapper for a 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:

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 :

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM