'lock ExtractToDirectory only runs once

This function takes a few seconds to run locally. It unpacks a zip file onto the local server and is called before serving individual files in the zip. It should only run once if the extracted folder does not exist.

internal static void Init(string releaseName)
{
    var unpackedFolderDirectory = Settings.Editor.FilesRootFolder + releaseName + "\\";
    var dirInfo = new DirectoryInfo(unpackedFolderDirectory);
    if (dirInfo.Exists) return;

    lock ("UnpackLock")
    {
        dirInfo.Refresh();
        if (dirInfo.Exists) return;

        // Unpack all
        var bytes = getBytesFromAzure();
        using var ms = new MemoryStream(bytes);
        using (var archive = new ZipArchive(ms))
        {
            archive.ExtractToDirectory(unpackedFolderDirectory);
        }
    }
}

If I make multiple requests to this function, some of them return the error:

The file 'C:\SomeFolder\SomeSubFolder\SomeFile.png' already exists.
On line -> archive.ExtractToDirectory(unpackedFolderDirectory);

I am expecting the archive.ExtractToDirectory(unpackedFolderDirectory); to only execute once, but it appears to be running multiple times.

What am I doing wrong? Is there some race condition here I'm not spotting?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source