-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUtilityFunctions.ps1
81 lines (70 loc) · 2.49 KB
/
UtilityFunctions.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
function Get-Mutex {
param([Parameter(Mandatory)][string]$MutexName)
$initiallyOwned = $false
$mutex = [System.Threading.Mutex]::new($initiallyOwned, $MutexName)
return $mutex
}
function Invoke-NewOrUpdateMemoryMappedFileContent {
param(
[Parameter(Mandatory)][string]$MapName,
[Parameter(Mandatory)][byte[]]$DataBytes
)
$MemoryMappedFileClass = [System.IO.MemoryMappedFiles.MemoryMappedFile]
$createOrOpenCapacity = $global:DataBytes.Length + 1
$memoryMappedFile = $MemoryMappedFileClass::CreateOrOpen($MapName, $createOrOpenCapacity)
# CreateViewStream() は使わない。
# CreateViewStream() は ローカル変数で viewStream を扱うときに、
# 稀にマップト・ファイルを作れないように見えるため。
$viewAccessor = $memoryMappedFile.CreateViewAccessor()
$viewAccessor.WriteArray(0, $DataBytes, 0, $DataBytes.Length)
$viewAccessor.Dispose()
}
function Get-MemoryMappedFileContentAsBytes {
param([Parameter(Mandatory)][string]$MapName)
$MemoryMappedFileClass = [System.IO.MemoryMappedFiles.MemoryMappedFile]
$memoryMappedFile = $MemoryMappedFileClass::OpenExisting($mapName)
$viewAccessor = $memoryMappedFile.CreateViewAccessor()
$capacity = $viewAccessor.Capacity
$bufferLength = $capacity
$buffer = New-Object byte[] $bufferLength
$viewAccessor.ReadArray(0, $buffer, 0, $buffer.Length) | Out-Null
$viewAccessor.Dispose()
return $buffer
}
function Invoke-NewOrUpdateMemoryMappedFileContentWithExclusiveControl {
param(
[Parameter(Mandatory)][System.Threading.Mutex]$Mutex,
[Parameter(Mandatory)][string]$MapName,
[Parameter(Mandatory)][byte[]]$DataBytes
)
try {
$Mutex.WaitOne() | Out-Null
Invoke-NewOrUpdateMemoryMappedFileContent -MapName $MapName -DataBytes $DataBytes
} catch {
throw $_
} finally {
$Mutex.ReleaseMutex()
}
}
function Get-MemoryMappedFileContentAsBytesWithExclusiveControl {
param(
[Parameter(Mandatory)][System.Threading.Mutex]$Mutex,
[Parameter(Mandatory)][string]$MapName
)
$buffer = $null
try {
$Mutex.WaitOne() | Out-Null
$buffer = Get-MemoryMappedFileContentAsBytes -MapName $MapName
} catch {
throw $_
} finally {
$Mutex.ReleaseMutex()
}
return $buffer
}
#function Invoke-StartSleep {
# param([Parameter(Mandatory)][int]$Seconds)
#
# Write-Host "Sleeping..."
# Start-Sleep $Seconds
#}