Skip to content
Prev Previous commit
Next Next commit
Update src/libraries/System.IO.FileSystem/tests/FileStream/DevicesPip…
…esAndSockets.cs


Use Lazy for thread-safety

Co-authored-by: Adam Sitnik <[email protected]>
  • Loading branch information
jozkee and adamsitnik authored Oct 11, 2021
commit 4378af051b79cc313fb208ff67bfc8052d68bd08
Original file line number Diff line number Diff line change
Expand Up @@ -162,41 +162,37 @@ private static async Task WriteByteAsync(FileStream fs, byte value)
await fs.FlushAsync();
}

private static List<string> _devicePathsAvailable;
private static List<string> GetDevicePaths()
private static Lazy<string[]> _availableDevicePaths = new Lazy<string[]>(() =>
{
if (_devicePathsAvailable is null)
List<string> paths = new();
FileStreamOptions options = new { Access = FileAccess.Write, Share = FileShare.Write };

foreach (string devicePath in new[] { "/dev/tty", "/dev/console", "/dev/null", "/dev/zero" })
{
var options = new FileStreamOptions { Access = FileAccess.Write, Share = FileShare.Write };
_devicePathsAvailable = new List<string>();
if (!File.Exists(devicePath))
{
continue;
}

foreach (string devicePath in new[] { "/dev/tty", "/dev/console", "/dev/null", "/dev/zero" })
try
{
if (!File.Exists(devicePath))
File.Open(devicePath, options).Dispose();
}
catch (Exception ex)
{
if (ex is IOException || ex is UnauthorizedAccessException)
{
continue;
}

try
{
File.Open(devicePath, options).Dispose();
}
catch (Exception ex)
{
if (ex is IOException || ex is UnauthorizedAccessException)
{
continue;
}

throw;
}

_devicePathsAvailable.Add(devicePath);
throw;
}

paths.Add(devicePath);
}

return _devicePathsAvailable;
}
return paths.ToArray();
});

public static IEnumerable<object[]> DevicePath_FileOptions_TestData()
{
Expand Down