1

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?

Joseph Anderson
  • 2,838
  • 2
  • 26
  • 26
  • It seems to me you might have quite a bit of overhead re-instantiating the library every time - especially since you're instantiating it inside the lock. It would probably be better to instantiate once and then refer to that instance later. – Anon. Dec 16 '09 at 20:39
  • Good point, Anon. Unfortunately the library needs to be re-instantiated for each call since the constructor sets the static vars. I've revised the example code above to reflect this. – Joseph Anderson Dec 16 '09 at 21:08

3 Answers3

2

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.

Matthias
  • 12,053
  • 4
  • 49
  • 91
0

Static constructor will help you:

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

Community
  • 1
  • 1
bniwredyc
  • 8,649
  • 1
  • 39
  • 52
0

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

Ariel
  • 5,752
  • 5
  • 49
  • 59