简体   繁体   中英

wcf singleton service multithreaded

I have a self hosted wcf singleton service. There are two client consuming it. Service has one instance variable of type List. There are three methods. One to add, one to remove and last to check if list is empty. Client1 is using only add method. Client2 uses remove and isEmpty method. I am wondering is lock required in this case in these methods? Any better approach for this problem to enhance performance?

[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;
        }
    }  
}

Well if one client adds while another removes and if you dont handle concurrency you could have trouble or inconsistent state.

So yes I would suggest a Lock or syncronization mechanism on the shared info/list

Are you doing it right? Yes, but this type of code is very hard to test. It's also hard to debug if you do make a mistake.

The better solution is to use a class that does it for you: ConcurrentQueue

Are you doing this right? NO!

What are you doing wrong? Reinventing the wheel.

It looks like you are trying to reinvent the MessageQueue pattern. The obvious solution, is to use a Message Queue software package.

PLEASE LOOK AT ONE OF THE FOLLOWING

  • MSMQ
  • RabbitMQ
  • Websphere
  • RavenMQ

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM