Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/273.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# wcf单例服务多线程_C#_Multithreading_Wcf - Fatal编程技术网

C# wcf单例服务多线程

C# wcf单例服务多线程,c#,multithreading,wcf,C#,Multithreading,Wcf,我有一个自我托管的wcf单例服务。有两个客户正在使用它。服务有一个列表类型的实例变量。有三种方法。一个要添加,一个要删除,最后一个检查列表是否为空。Client1仅使用add方法。Client2使用remove和isEmpty方法。我想知道这些方法在这种情况下是否需要锁?有没有更好的方法来解决此问题以提高性能 [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single,ConcurrencyMode = Concurrenc

我有一个自我托管的wcf单例服务。有两个客户正在使用它。服务有一个列表类型的实例变量。有三种方法。一个要添加,一个要删除,最后一个检查列表是否为空。Client1仅使用add方法。Client2使用remove和isEmpty方法。我想知道这些方法在这种情况下是否需要锁?有没有更好的方法来解决此问题以提高性能

[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
  • 拉文姆克

当你说“增强性能”时,你能说明你的意思吗?什么是慢的,您是如何测量的?@marc_s ConcurrencyMode=ConcurrencyMode.Multiple它不允许同时有多个线程吗?@MauricioGracia如果不需要锁定,并且我正在使用它,它会使这个速度变慢(每秒处理的请求数量)。不是吗?因此,一些技术将允许它处理更多的请求。我这样做的方式…是正确的吗?或者有更好的方法吗?@dream\u machine,比如@dream\u machine,这里也提到了一些重要的注释@dream\u machine,也就是这个