我觉得我在重新发明轮子,而且很有可能有人已经用头撞到代码上,想出了一个好的、稳定的、经过测试的模式来解决这个问题,而我没有还没有遇到。
我想出了以下似乎对我有用的解决方案。
它应该提供一个一致的接口来处理应该以线程安全方式访问的对象。
@pst称其为“原子”对象 get/set holder,这是在其他地方使用的模式吗?
这是界面:
public interface ISynched<T>
{
bool Read( ref T value );
bool Read( ref T value, TimeSpan timeout );
bool Write( T value );
bool Write( T value, TimeSpan timeout );
bool Do( Action<T> roAction );
bool Do( Action<T> roAction, TimeSpan timeout );
bool Do( Action<T, Action<T>> rwAction );
bool Do( Action<T, Action<T>> rwAction, TimeSpan timeout );
}
实现如下:
public class Synched<T>: ISynched<T>
{
static public readonly TimeSpan Infinity = TimeSpan.FromMilliseconds(-1);
private T _value;
public static Synched<T> MakeSynched( T value )
{
return new Synched<T>() { _value = value };
}
private Synched() {}
public bool Read( ref T value )
{
return Read( ref value, Infinity );
}
public bool Read( ref T value, TimeSpan timeout )
{
var tmp = default(T);
var success = Do( (v) => tmp = v, timeout );
if( success ) value = tmp;
return success;
}
public bool Write( T value )
{
return Do( (v, set) => set(v) );
}
public bool Write( T value, TimeSpan timeout )
{
return Do( (v, set) => set(v), timeout );
}
public bool Do( Action<T> roAction )
{
return Do( roAction, Infinity );
}
public bool Do( Action<T> roAction, TimeSpan timeout )
{
bool lockWasTaken = false;
try
{
Monitor.TryEnter(this, timeout, ref lockWasTaken);
if(!lockWasTaken) return false;
roAction( _value );
return true;
}
finally
{
if (lockWasTaken) Monitor.Exit(this);
}
}
public bool Do( Action<T, Action<T>> rwAction )
{
return Do( rwAction, Infinity);
}
public bool Do( Action<T, Action<T>> rwAction, TimeSpan timeout )
{
bool lockWasTaken = false;
try
{
Monitor.TryEnter(this, timeout, ref lockWasTaken);
if(!lockWasTaken) return false;
rwAction( _value, value => _value = value );
return true;
}
finally
{
if (lockWasTaken) Monitor.Exit(this);
}
}
}
还有一个额外的静态非泛型类,可以更轻松地编写同步对象创建代码:
public static class Synched
{
public static Synched<T> MakeSynched<T>( T value )
{
return Synched<T>.MakeSynched( value );
}
}
编辑:我已经更改了示例以使其更有意义示例用例看起来像这样(代码没有任何意义,只是一个示例(一个不好的示例):
var synchedCol = Synched.MakeSynched( new List<SomeClass>() );
synchedCol.Do( c => {
c.Add(new SomeClass());
c.Add(new SomeClass() { Property1 = "something" } );
} );
var i = 1;
SomeClass val;
synchedCol.Do( c => val = c[i] );
var i = 1;
synchedCol.Do( c => {
if( c[i].Property1 == "something" )
{
c.Remove(c[i]);
}
});
那么我在正确的轨道上吗?有没有人遇到过类似的事情?有没有类似的现有模式?