views:

173

answers:

3

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?

A: 

Static constructor will help you:

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

bniwredyc
+2  A: 

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.

winSharp93
A: 

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

Ariel