Managing concurrent access
When writing code that runs asynchronously, it can be desirable to write to a resource that does not support concurrent access. For example, when writing to a log file, Windows will not allow two simultaneous write operations to a file.
Consider the following script. This script does nothing more than write a log file entry:
$script = {
param (
$Path,
$RunspaceName
)
# Some long running activity
$message = '{0:HH:mm:ss.fff}: Writing from runspace {1}' -f @(
Get-Date
$RunspaceName
)
[System.IO.File]::AppendAllLines(
$Path,
[string[]]$message
)
}
The script uses the AppendAllLines
method instead of a command like Add-Content
as it better exposes an error that shows the problem with the script.
Before starting, ensure the runspace.log
file does not exist:
Remove-Item runspace.log
When multiple instances of this script run, there are potentially attempts...