I am developing a base class that, when inherited, will provide business functionality for context in a multi-threaded environment. Each instance can have lengthy initialization operations, so I want to make objects multiple. To do this, I need to be able to:
- Assign a context to one of these objects so that it can do its job.
- Prevent assignment of an object to a new context when it already has
- Prevent access to specific members while the object has no context
In addition, each context object can be shared by many work objects.
Is there a correct synchronization primitive that matches what I'm trying to do? This is the sample I came up with that best fits what I need:
private Context currentContext; internal void BeginProcess(Context currentContext) { // attempt to acquire a lock; throw if the lock is already acquired, // otherwise store the current context in the instance field } internal void EndProcess() { // release the lock and set the instance field to null } private void ThrowIfNotProcessing() { // throw if this method is called while there is no lock acquired }
Using the above, I can protect the properties and methods of the base class that should not be accessed, unless the object is in processing state.
protected Context CurrentContext { get { this.ThrowIfNotProcessing(); return this.context; } } protected void SomeAction() { this.ThrowIfNotProcessing();
At first, I wanted to use Monitor.Enter and related functions, but this does not interfere with reconnecting a single thread (several calls to BeginProcess in the original topic).
source share