简体   繁体   中英

C# DLL - multiple class objects from Assembly

I have a Assembly (Server.dll) which receives an input string and returns an appended string to it.

I use the dll this way:

    using ServerDll;

    ServerDll.Server ob = new ServerDll.Server();
    for ( int i = 0 ; i<10; i++ )
    {
        Console.WriteLine(   ob.GiveAppendedString("Hello")    );
    }

Now, I use this assembly in many Asynchronous threads. So in each thread, I use the code from above.

In different threads, I am able to create the Server object, but, I notice that only one thread is able to use the function GiveAppendedString() in the loop at a time. No two threads are able to use the method exposed by the DLL at the same time in their respective loops.

How can I achieve multi-threaded and concurrent calls to the function GiveAppendedString() from all threads ?

Should I use any multi-threaded apartment model? If yes, are there any weblinks to the steps that I should take as I am novice in this area.

Thanks.

[ UPDATE ] Simplified question: Can a function of an assembly be called by multiple threads ( from an application that references the assembly ) at the same time? If yes, how ?

Edit: To answer your updated, simplified question: Yes . You need to write the function in a threadsafe manner. This is usually a non trivial task, and you need to make sure that all code called by GiveAppendedString is either threadsafe or put in a lock scope.

That is what locking is for. Wrap the call in a lock() {...} scope, eg

    ServerDll.Server ob = new ServerDll.Server();
    for ( int i = 0 ; i<10; i++ )
    {
        string appendedString;
        lock(ob)
        {
            ob.GiveAppendedString("Hello");
        }
        Console.WriteLine(appendedString);
    }

Or, alternatively, make GiveAppendedString thread safe if possible.

The case depends entirely on the implementation of the GiveAppendedString() . If the function is implemented with a lock then it is meant to be running synchronously (or rather not concurrently) for the instance.

For other cases, you can use any asynchronous techniques to perform concurrent calls. Based on your code, I've provided an example for making concurrent calls here,

  Parallel.For(0, 10,
                    i =>
                    {
                        Console.WriteLine(ob.GiveAppendedString("Hello"));
                    });

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