WCF Web服务单例 - 奇怪的行为

时间:2011-05-27 09:01:21

标签: multithreading wcf web-services singleton

我创建了一个单独的WCF Web服务,它在托管时的整个时间内运行后台线程。第一种方法在后台线程中启动一个函数,该函数检查共享数据,另一个方法更新该数据。它工作正常,突然开始表现得很奇怪。同时代码没有重大变化。 WCF Web服务托管在Visual Studio开发服务器,VS2008,3.5框架,Win XP SP3中,如果它在IIS 7上托管在Vista中,也会发生同样的情况。

这是简化代码

服务:

[ServiceContract]
public interface IService1
{
    [OperationContract]
    void Configure(XElement configuration);

    [OperationContract]
    void UpdateData(string data);               
}

[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]
public partial class Service1 : IService1
{
    List<string> stringCollection = new List<string>();
    bool running;
    Thread workerThread;

    public void Configure(XElement configuration)
    {
        //add string elements to the stringCollection based on configuration
        ParseConfiguration(); //implementation is irrelevant

        //start background thread
        workerThread = new Thread(WorkerFunction);
        running = true;
        workerThread.Start();
    }

    public void UpdateData(string data)
    {
        //adds string data to stringCollection
        stringCollection.Add(data);
    }
}

public partial class Service1 : IService1
{
    private void WorkerFunction()
    {
        while(running)
        {
            //check stringCollection
            Thread.Sleep(500);
        }
    }
}

客户端:

//Configure() is called first and only once from client
Xelement configuration = Xelement.Load("configuration.xml");
ServiceReference1.Service1Client client = new ServiceReference1.Service1Client();
client.Configure(configuration);
client.Close();

//UpdateData is called repeatedly from client
ServiceReference1.Service1Client client = new ServiceReference1.Service1Client();
client.UpdateData("some string");
client.Close();

调试时我注意到了几件事。在Configure()在新线程中启动WorkerFunction()之后,该线程处于活动状态一秒左右,而WorkerFunction()可以访问在Configure()中配置的stringCollection。当客户端第一次调用UpdateData()方法时,该方法具有空的stringCollection(不包含从Configure()方法添加的数据),就好像它没有共享,而stringCollection在每次UpdateData()调用之间保留其数据。例如:

//stringCollection after Configure()
{"aaa","bbb","ccc"}

//stringCollection after UpdateData("xxx")
{"xxx"}

//stringCollection after UpdateData("yyy")
{"xxx", "yyy"}

//after I run Client application again and call Configure()
//the data is preserved only here
{"xxx", "yyy","aaa", "bbb", "ccc"}

如果我在调试时在Threads窗口中以最高优先级继承Thread,那么后台线程会保持活动状态,就像它应该做的那样但是我得到的结果与上面相同。 WorkerFunction()有自己的stringCollection实例,UpdateData()有另一个实例。我不知道具有最高优先级的线程与我的后台线程有什么关系,但它似乎对它有不良影响。服务应该是单身,但它不像一个人。

干杯

1 个答案:

答案 0 :(得分:0)

很高兴看到您的问题已修复。

但是,我认为你应该看一下你的代码,它似乎比它需要的更复杂。

您正在使用Singleton,但每次调用singleton都会创建一个新线程。

为什么不在没有singlton的情况下这样做,让IIS处理线程?