简体   繁体   中英

WCF service hosted Windows Service not saving state between calls

I am trying to make a simple windows service that maintains a queue of integers and accepts new integers from other applications via a WCF call. My current implementation seems to maintain separate queues for each application which communicates with it, which is not what I want.

I started by following the instructions at from Microsoft on How to: Host a WCF Service in a Managed Windows Service .

My WindowsService class looks like this:

public class MyWindowsService : ServiceBase{
    public ServiceHost serviceHost = null;

    public MyWindowsService(){
        ServiceName = "AdHocReportService";
    }
    public static void Main(){
        ServiceBase.Run(new MyWindowsService());
    }

    protected override void OnStart(string[] args){
        if (serviceHost != null)
            serviceHost.Close();

        serviceHost = new ServiceHost(typeof(MyService));
        serviceHost.Open();
    }
    protected override void OnStop(){
        if (serviceHost != null){
            serviceHost.Close();
            serviceHost = null;
        }
    }
}

In my Service class I have a queue and an Add method. The add method returns the count of items in the queue after the add. The code looks like this:

public class MyService : IMyService
{
    private Queue<int> myQueue= new Queue<int>();

    public int Add(int reportId)
    {
        myQueue.Enqueue(reportId);
        return myQueue.Count;
    }
}

Lastly, I test my service using the following code in a ConsoleApp:

MyServiceClient client = new MyServiceClient();
int count = client.Add(10);
Console.WriteLine(count);  //prints 1
count = client.Add(25);
Console.WriteLine(count);  //prints 2
Console.ReadLine();

I would expect this to print 1 and 2 the first time my test is run, then 3 and 4 the second time, and then 5 and 6 the third and so on. However, it simply returns 1 and 2 each time, as if the Console App is instantiating the object itself and not operating on the object inside the Windows Service. What am I not understanding?

I think you want a singleton WCF service. See here .

By default, the instance mode for a WCF service is per-call . So an instance of your service is being created by the host for each call you make.

Note: When using a singleton service, your operations need to be thread safe . So I suggest switching from a Queue to a ConcurrentQueue , so you can handle multiple concurrent clients.

Alternative: Use a MSMQ binding . This will ensure you that all of your incoming messages are queued out of process, therefore persisted between restarts too.

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