简体   繁体   中英

Sharing objects between threads in C# and WCF

I have a server which exposes a SOAP WCF service endpoint. This server also uses a group communication framework called Ensemble (not really relevant to the question) in order to communicate with other servers in the same cluster.

I need to share objects/data between the seperate thread which listens for incoming messages from other servers and the threads that run the WCF routines when they are invoked. So far, I did the most simple thing I could think of - I created a static "database" class with static members and static methods - and used lock() to sync. This way I could access this class from both the server and the group communication thread. My problem with this is that it kinda breaks the whole "OOP thing" and I think something more clever can be done here...

If the only issue that you have with your solution is its alleged "non-OOP-edness", you could go for the Singleton Pattern instead. This is a widely used pattern for situations when you must have a single instance of a class that needs to be shared among multiple parts of the system that are otherwise disconnected. The pattern remains somewhat controversial, because some regard it as a glorified version of a global variable, but it is efficient at getting the job done.

Encapsulate the seperate thread which listens for incoming messages from other servers into a Class say MyCustomService.

Write the WCF service Implementation class with behaviour as concurrencyMode multiple and InstanceContextMode Single

Write a event delagate inside the WCF service implementation class. The delegate will return type of the MyCustomService class.

When you instantiate the WCF service programmatically, (host.Open), before that set the delegate to a function that will return the MyCustomService instance which can be singleton or static.

From the service instance class you can always call the delegate to get the MyCustomService instance. Check for null though.

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