Wait For Exclusive Access : Thread Lock « Thread « C# / C Sharp

Home
C# / C Sharp
1.2D Graphics
2.Class Interface
3.Collections Data Structure
4.Components
5.Data Types
6.Database ADO.net
7.Date Time
8.Design Patterns
9.Development Class
10.Event
11.File Stream
12.Generics
13.GUI Windows Form
14.Internationalization I18N
15.Language Basics
16.LINQ
17.Network
18.Office
19.Reflection
20.Regular Expressions
21.Security
22.Services Event
23.Thread
24.Web Services
25.Windows
26.Windows Presentation Foundation
27.XML
28.XML LINQ
C# / C Sharp » Thread » Thread LockScreenshots 
Wait For Exclusive Access
        

using System;
using System.IO;
using System.Threading;

namespace jQueryBuddy.Utilities
{
    public class FileUtilities
    {
        public static bool WaitForExclusiveAccess(string filename, int timeout)
        {
            const int retryPause = 100;

            var startTime = DateTime.Now.Ticks;
            do
            {
                try
                {
                    // Try to open the file for exclusive access
                    using (new FileStream(filename, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
                    {
                        return true;
                    }
                }
                // Not ideal checking for an exception, especially one which may be raised for a number of
                // reasons but this may be the only way.
                catch (IOException)
                {
                    Thread.Sleep(retryPause);
                }
            while (new TimeSpan(DateTime.Now.Ticks - startTime).TotalSeconds < timeout);

            return false;
        }
    }
}

   
    
    
    
    
    
    
    
  
Related examples in the same category
1.illustrates the use of the lock objectillustrates the use of the lock object
2.illustrates the use of the Interlocked objectillustrates the use of the Interlocked object
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.