C# wcf单例服务多线程
我有一个自我托管的wcf单例服务。有两个客户正在使用它。服务有一个列表类型的实例变量。有三种方法。一个要添加,一个要删除,最后一个检查列表是否为空。Client1仅使用add方法。Client2使用remove和isEmpty方法。我想知道这些方法在这种情况下是否需要锁?有没有更好的方法来解决此问题以提高性能C# wcf单例服务多线程,c#,multithreading,wcf,C#,Multithreading,Wcf,我有一个自我托管的wcf单例服务。有两个客户正在使用它。服务有一个列表类型的实例变量。有三种方法。一个要添加,一个要删除,最后一个检查列表是否为空。Client1仅使用add方法。Client2使用remove和isEmpty方法。我想知道这些方法在这种情况下是否需要锁?有没有更好的方法来解决此问题以提高性能 [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single,ConcurrencyMode = Concurrenc
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single,ConcurrencyMode = ConcurrencyMode.Multiple)]
public class Service : IService
{
// will it be better to make it static ?
List<Parameter> _fileList = new List<Parameter>();
// Is this required ?
readonly object _lock = new object();
public bool FileEnQueue(Parameter parameter)
{
lock (_lock)
{
_fileList.Add(parameter);
}
return true;
}
public Parameter FileDeQueue()
{
lock (_lock)
{
Parameter parameter = new Parameter();
if (_fileList.Count > 0)
{
parameter = _fileList.ElementAt(0);
_fileList.Remove(parameter);
}
return parameter;
}
}
public bool IsQueueEmpty()
{
lock (_lock)
{
if (_fileList.Count == 0)
return true;
else
return false;
}
}
}
[服务行为(InstanceContextMode=InstanceContextMode.Single,ConcurrencyMode=ConcurrencyMode.Multiple)]
公共课服务:IService
{
//让它静止会更好吗?
列表_fileList=新列表();
//这是必需的吗?
只读对象_lock=新对象();
公共bool文件队列(参数)
{
锁
{
_fileList.Add(参数);
}
返回true;
}
公共参数FileDeQueue()
{
锁
{
参数=新参数();
如果(_fileList.Count>0)
{
参数=_fileList.ElementAt(0);
_fileList.Remove(参数);
}
返回参数;
}
}
公共bool IsQueueEmpty()
{
锁
{
如果(_fileList.Count==0)
返回true;
其他的
返回false;
}
}
}
如果一个客户端添加而另一个客户端删除,并且如果您不处理并发,则可能会遇到问题或状态不一致
因此,是的,我建议在共享信息/列表上使用锁定或同步机制,你这样做对吗?是的,但是这类代码很难测试。如果您确实犯了错误,那么调试也很困难
更好的解决方案是使用一个为您做这件事的类:您做得对吗?不 你做错了什么?重新发明轮子 看起来您正在尝试重新创建
MessageQueue
模式。显而易见的解决方案是使用消息队列软件包
请看下面的一个例子
- MSMQ
- 兔子
- Websphere
- 拉文姆克