为非线程安全代码构建工作线程池
在 .net 框架中包装非线程安全代码的最佳方法是什么?
我有一个第三方库,由于使用静态变量,该库不是线程安全的。重写它不是一个选择。该库由接收大量并发调用的 ASP.NET Web 服务使用。
我目前已将其包装在一个代理类中,该代理类使用锁来确保线程安全:
private static readonly object oneThreadAtATimePlease = new object();
public ISomething CalculateSomething(int someValue)
{
lock (oneThreadAtATimePlease)
{
return new UnsafeLibrary(someValue).DoSomething();
}
}
性能很差,因为多个调用者必须等待锁,但结果是正确的。
我想通过运行该库的多个实例(每个实例都在其自己的 AppDomain 中)来提高性能。这是一个合理的做法吗?有什么好的示例代码可以推荐吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您还可以尝试使用队列创建基于消息的应用程序。
然后,多个线程可以对请求进行排队,并且一个线程可以处理该队列并将结果通知其他线程。
使用监视器类并不总是最快的方法。
AppDomains 是一个选项。然而,你将不得不处理IPC。
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.
静态构造函数将帮助您:
静态构造函数保证仅运行每个应用程序域一次...
Static constructor will help you:
Static constructors are guaranteed to be run only once per application domain...
如果一个 Singleton 只包含一个工作对象实例以及一个请求队列呢?
What about a Singleton containing only one instance of the worker object, plus a requests queue?