Joseph Anderson
Joseph Anderson

Reputation: 2848

Building a worker thread pool for a non-thread-safe code

What's the best way to wrap non-thread-safe code in the .net framework?

I've got a third-party library that isn't thread safe due to its use of static variables. Rewriting it isn't an option. This library is used by an asp.net web service that receives lots of simultaneous calls.

I've currently got it wrapped in a proxy class that uses locks to ensure thread safety:

private static readonly object oneThreadAtATimePlease = new object();
public ISomething CalculateSomething(int someValue)
{
    lock (oneThreadAtATimePlease)
    {
        return new UnsafeLibrary(someValue).DoSomething();
    }
}

Performance is poor since multiple callers have to wait for the lock, but the results are correct.

I'd like to improve performance by running multiple instances of this library, each in its own AppDomain. Is this a reasonable approach? Any good sample code to recommend?

Upvotes: 1

Views: 473

Answers (3)

Ariel
Ariel

Reputation: 5830

What about a Singleton containing only one instance of the worker object, plus a requests queue?

Upvotes: 0

Matthias
Matthias

Reputation: 12259

You could also try to create a message based application using a queue.

Then multiple threads could queue requests and one single thread could work on this queue and notify the other threads about the results. Using the monitor class is not always the fastest way.

AppDomains are an option. However, you will have to deal with IPC.

Upvotes: 2

bniwredyc
bniwredyc

Reputation: 8839

Static constructor will help you:

Static constructors are guaranteed to be run only once per application domain...

Upvotes: 0

Related Questions