这种同步结构正确吗?
我有一个多线程应用程序。线程使用 ABC.Connector。我希望一次只有一个线程可以访问连接器属性。
class ABC
{
/// <summary>
/// Synchronization object.
/// </summary>
static object _syncObject = new object();
static DataAccess _connector;
/// <summary>
/// Global object for data access.
/// </summary>
public static DataAccess Connector
{
get
{
lock (_syncObject)
{
return _connector.CreateCopy(); // get a copy of original _connector
}
}
set
{
lock (_syncObject)
{
_connector = value;
}
}
}
}
正确吗?
I have a multi-threaded application. Threads use ABC.Connector. I want that only one thread at a time have access to a Connector property.
class ABC
{
/// <summary>
/// Synchronization object.
/// </summary>
static object _syncObject = new object();
static DataAccess _connector;
/// <summary>
/// Global object for data access.
/// </summary>
public static DataAccess Connector
{
get
{
lock (_syncObject)
{
return _connector.CreateCopy(); // get a copy of original _connector
}
}
set
{
lock (_syncObject)
{
_connector = value;
}
}
}
}
Is it correct ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好吧,这肯定会使获取和设置
Connector
属性成为线程安全的(尽管我会将_syncObject
设为只读)。但是,它并不使DataAccess
线程安全...互斥体仅在线程获取和设置属性时应用。。换句话说,如果两个线程都执行以下操作:
则两个线程仍将同时运行
DoSomeLongRunningOperation()
。如果该操作不是线程安全的,它仍然会是一个问题。如果您一次只希望一个线程使用
DataAccess
,那么您可以这样写:那么如果两个线程都这样做:
那么
DoLongRunningOperation()
一次只会在一个线程中运行。您仍然遇到行为不端的客户可能会写的问题:...但希望这对您来说不是问题。
Well, that will certainly make getting and setting the
Connector
property thread-safe (although I'd make_syncObject
read-only). However, it doesn't makeDataAccess
thread-safe... the mutex will only apply while threads are getting and setting the property.In other words, if two threads both do:
then
DoSomeLongRunningOperation()
will still be run concurrently by the two threads. If that operation isn't thread-safe, it's still going to be a problem.If you only want one thread at a time to use the
DataAccess
then you could write:Then if two threads both do:
then
DoLongRunningOperation()
will only run in one thread at a time. You've still got the issue that misbehaving clients could write:... but hopefully that isn't an issue for you.
是的,这通常是正确的。但请注意,在 Connector get 返回 _connector 引用后,对其的访问是不同步的。
Yes, this is generally correct. But take into account, that after Connector get returns the _connector reference, access to it is unsynchronized.