System.IO.FileStream.Lock C# (CSharp) Method

Lock() public method

public Lock ( long position, long length ) : void
position long
length long
return void
        public virtual void Lock(long position, long length)
        {
            if (position < 0 || length < 0)
            {
                throw new ArgumentOutOfRangeException(position < 0 ? nameof(position) : nameof(length), SR.ArgumentOutOfRange_NeedNonNegNum);
            }

            if (_fileHandle.IsClosed)
            {
                throw Error.GetFileNotOpen();
            }

            LockInternal(position, length);
        }

Usage Example

Exemplo n.º 1
0
        public FileSystemExclusiveLock(string pathToLock, ILog log)
        {
            EnsureTargetFile(pathToLock, log);

            var success = false;

            //Unfortunately this is the only filesystem locking api that .net exposes
            //You can P/Invoke into better ones but thats not cross-platform
            while (!success)
            {
                try
                {
                    _fileStream = new FileStream(pathToLock, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
                    // Oh and there's no async version!
                    _fileStream.Lock(0, 1);
                    success = true;
                }
                catch (IOException)
                {
                    success = false;
                    //Have I mentioned that I hate this algorithm?
                    //This basically just causes the thread to yield to the scheduler
                    //we'll be back here more than 1 tick from now
                    Thread.Sleep(TimeSpan.FromTicks(1));
                }
            }
        }
All Usage Examples Of System.IO.FileStream::Lock