The purpose of this class is to allow exchange data between different processes on the same machine.The idea is to use temporary files, in a common directory, that are shared to all processes (i.e. c:\windows\temp) and synchronize access to these files through System.Threading.Mutex objects.
Prerequisites:
- The processes must reside on the same machine;
- There must be a local or remote directory accessible to all processes
- Objects that can be exchanged must be serializable (at least in binary format).
Limitations:
It is not possible to exchange data on a cluster system (active-active) or on back-end machines behind a load balancer such as NLB.
Possible uses:
- Inter Process Communication and data exchange of primitive types and/or complex types (custom classes that are serializable);
- Data exchange between Two or more applications, COM <==> NET, ASP <==> ASP.NET, and so on. [Shared Storage class is COM visible]
Mutex and Temporary files:
When two or more threads/processes need to access a shared resource at the same time, the system needs a synchronization mechanism to ensure that only one thread/process at a time uses the resource.
Mutex is a synchronization primitive that grants exclusive access to the shared resource to only one thread. If a thread/process acquires a mutex, the second thread (in the same or another process) that wants to acquire that mutex is suspended until the first thread/process releases the mutex.
Exclusive file write:
using System.IO;
using System.Threading;
public bool AddOrUpdate(string objectName, objectobjectValue)
{
bool createdNew = false;
(Mutex mLocked = new Mutex(true,String.Format(SharedStorage.
MUTEX_LOCKED_FORMAT, this.storageName), out createdNew))
{
try
{
if (!createdNew)
mLocked.WaitOne(); //Another thread/process is using it
bool fileCreated = this.writeFile(objectName, objectValue);
//false if overwrite
if (fileCreated && this.destroyWhenDisposed)
this.createdFiles.Add(this.getStorageFileName(objectName));
return fileCreated;
}
finally
{
mLocked.ReleaseMutex();
}
}
}
Exclusive file read:
using System.IO;
using System.Threading;
public object this[string objectName]
{
get
{
bool createdNew = false;
using (Mutex mLocked = new Mutex(true,String.Format(SharedStorage.MUTEX_LOCKED_FORMAT, this.storageName), out createdNew))
{
try
{
if (!createdNew)mLocked.WaitOne(); //Another thread/process is using it
if (this.Exists(objectName))return this.readFile(objectName);
else throw new ArgumentOutOfRangeException ("objectName",
String.Format("'{0}' object not found.",objectName));
}
finally
{
mLocked.ReleaseMutex();
}
}
}
}
0 comments:
Post a Comment