我创建了一个单例WCF Web服务,该服务在托管时始终在后台运行线程。第一种方法在后台线程中启动一个用于检查共享数据的函数,而另一个则更新该数据。它工作正常,突然开始表现怪异。同时,代码没有重大变化。 WCF Web服务托管在Visual Studio Development Server,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"}
如果我在调试时在“线程”窗口中以最高优先级挂起线程,则后台线程会像预期的那样保持 Activity 状态,但是我得到的结果与上述相同。 WorkerFunction()具有自己的stringCollection实例,而UpdateData()具有另一个实例。我不知道该优先级最高的线程与我的后台线程有什么关系,但似乎对它有不好的影响。服务应该是单例的,但它的行为不像单例。
干杯
最佳答案
很高兴看到您的问题已解决。
但是,我认为您应该稍微看一下代码,它看起来比需要的复杂。
您使用的是Singleton,但是每次调用Singleton都会创建一个新线程。
为什么没有singlton而不让IIS处理线程呢?
关于multithreading - WCF Web服务单例-奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6150005/