public async Task CreateLockAsync()

in src/PowerShell/Utilities/CrossPlatformLock.cs [92:140]


        public async Task CreateLockAsync(CancellationToken cancellationToken = default)
        {
            Exception exception = null;
            FileStream fileStream = null;

            // Create lock file dir if it doesn't already exist
            Directory.CreateDirectory(Path.GetDirectoryName(lockFilePath));

            for (int tryCount = 0; tryCount < LockfileRetryCountDefault; tryCount++)
            {

                try
                {
                    // We are using the file locking to synchronize the store, do not allow multiple writers or readers for the file.
                    FileShare fileShare = FileShare.None;

                    if (SharedUtilities.IsWindowsPlatform())
                    {
                        // This is so that Windows can offer read due to the granularity of the locking. Unix will not
                        // lock with FileShare.Read. Read access on Windows is only for debugging purposes and will not
                        // affect the functionality.
                        //
                        // See: https://github.com/dotnet/coreclr/blob/98472784f82cee7326a58e0c4acf77714cdafe03/src/System.Private.CoreLib/shared/System/IO/FileStream.Unix.cs#L74-L89
                        fileShare = FileShare.Read;
                    }

                    fileStream = new FileStream(lockFilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, fileShare, DefaultBufferSize, FileOptions.DeleteOnClose);

                    using (StreamWriter writer = new StreamWriter(fileStream, Encoding.UTF8, DefaultBufferSize, leaveOpen: true))
                    {
                        await writer.WriteAsync($"{Process.GetCurrentProcess().Id} {Process.GetCurrentProcess().ProcessName}").ConfigureAwait(false);

                    }
                    break;
                }
                catch (IOException ex)
                {
                    exception = ex;
                    await Task.Delay(LockfileRetryDelayDefault, cancellationToken).ConfigureAwait(false);
                }
                catch (UnauthorizedAccessException ex)
                {
                    exception = ex;
                    await Task.Delay(LockfileRetryCountDefault, cancellationToken).ConfigureAwait(false);
                }
            }

            lockFileStream = fileStream ?? throw new InvalidOperationException("Could not get access to the shared lock file.", exception);
        }