I have a web application that controls which web applications receive served traffic from our load balancer. The web application runs on each individual server.
It tracks the entry or exit state for each application in the object in the ASP.NET application state, and the object is serialized to a file on disk whenever the state changes. The state is deserialized from the file when the web application starts.
While the site itself receives a couple of requests at the second top and a file that it rarely accesses, I found that for some reason it was very easy to get collisions when trying to read or write to a file. This mechanism must be extremely reliable, because we have an automated system that regularly performs deployment deployments on the server.
Before anyone makes any comments questioning the prudence of any of the above, let me just say that explaining the reasons why it would have made this message much longer than it is, so I would like to avoid moving mountains.
However, the code I use to control access to the file is as follows:
internal static Mutex _lock = null;
private static Boolean InvokeOnFile(Func<FileStream, Object> func, out Object result)
{
var l = new Logger();
if (ServerState._lock.WaitOne(1500, false))
{
l.LogInformation( "Got lock to read/write file-based server state."
, (Int32)VipEvent.GotStateLock);
var fileStream = File.Open( ServerState.PATH, FileMode.OpenOrCreate
, FileAccess.ReadWrite, FileShare.None);
result = func.Invoke(fileStream);
fileStream.Close();
fileStream.Dispose();
fileStream = null;
ServerState._lock.ReleaseMutex();
l.LogInformation( "Released state file lock."
, (Int32)VipEvent.ReleasedStateLock);
return true;
}
else
{
l.LogWarning( "Could not get a lock to access the file-based server state."
, (Int32)VipEvent.CouldNotGetStateLock);
result = null;
return false;
}
}
, ( " " ). - (Win Server 2k3/IIS 6). -, ( ?), .
, , , .
Application_Start. , .
, : / - , .
, ?
Update:
( !), - .
- - - , . , , - , WP , , , , , .
@mmr: Monitor, Mutex? MSDN, , - Mutex, , false.
: , , - , . , (, , ).
2:
. , _lock InvokeOnFile, .
Func - , , . .
ServerState.PATH - readonly, , concurrency.
, ( Cassini).
:
- (duh!)
- ( , / ). , Mutex, -, , , Monitor .NET.