File Access Strategy in a Multi-Threaded Environment (Web App)

前端 未结 5 1090
南笙
南笙 2021-01-05 16:25

I have a file which is an XML representation of some data that is taken from a Web service and cached locally within a Web Application. The idea being is that this data is <

5条回答
  •  不知归路
    2021-01-05 17:10

    Here is the code that I use to make sure a file is not locked by another process. It's not 100% foolproof, but it gets the job done most of the time:

        /// 
        /// Blocks until the file is not locked any more.
        /// 
        /// 
        bool WaitForFile(string fullPath)
        {
            int numTries = 0;
            while (true)
            {
                ++numTries;
                try
                {
                    // Attempt to open the file exclusively.
                    using (FileStream fs = new FileStream(fullPath,
                        FileMode.Open, FileAccess.ReadWrite, 
                        FileShare.None, 100))
                    {
                        fs.ReadByte();
    
                        // If we got this far the file is ready
                        break;
                    }
                }
                catch (Exception ex)
                {
                    Log.LogWarning(
                       "WaitForFile {0} failed to get an exclusive lock: {1}", 
                        fullPath, ex.ToString());
    
                    if (numTries > 10)
                    {
                        Log.LogWarning(
                            "WaitForFile {0} giving up after 10 tries", 
                            fullPath);
                        return false;
                    }
    
                    // Wait for the lock to be released
                    System.Threading.Thread.Sleep(500);
                }
            }
    
            Log.LogTrace("WaitForFile {0} returning true after {1} tries",
                fullPath, numTries);
            return true;
        }
    

    Obviously you can tweak the timeouts and retries to suit your application. I use this to process huge FTP files that take a while to be written.

提交回复
热议问题