public override bool Obtain()
{
lock (this)
{
FailureReason = null;
if (Channel != null)
{
// Our instance is already locked:
return false;
}
if (!System.IO.Directory.Exists(LockDir.FullName))
{
try
{
System.IO.Directory.CreateDirectory(LockDir.FullName);
}
catch
{
throw new System.IO.IOException("Cannot create directory: " + LockDir.FullName);
}
}
else if (File.Exists(LockDir.FullName))
{
throw new IOException("Found regular file where directory expected: " + LockDir.FullName);
}
var success = false;
try
{
Channel = new FileStream(Path.FullName, FileMode.Create, FileAccess.Write, FileShare.None);
Channel.Lock(0, Channel.Length);
success = true;
}
catch (IOException e)
{
FailureReason = e;
IOUtils.CloseWhileHandlingException(Channel);
Channel = null;
}
// LUCENENET: UnauthorizedAccessException does not derive from IOException like in java
catch (UnauthorizedAccessException e)
{
// On Windows, we can get intermittent "Access
// Denied" here. So, we treat this as failure to
// acquire the lock, but, store the reason in case
// there is in fact a real error case.
FailureReason = e;
IOUtils.CloseWhileHandlingException(Channel);
Channel = null;
}
finally
{
if (!success)
{
IOUtils.CloseWhileHandlingException(Channel);
Channel = null;
}
}
return Channel != null;
}
}