-
Notifications
You must be signed in to change notification settings - Fork 214
Description
Reproduction steps:
$requiredModules = @(
'Microsoft.Graph.Authentication'
'Microsoft.Graph.Groups'
)
$jobs = @()
1..50 | ForEach-Object {
$jobs += Start-RSJob -Name "Add group: {$_}" -ModulesToImport $requiredModules -Throttle 10 -ScriptBlock {
$grp = New-MgGroup -DisplayName "new-mggroup-thread-test" -MailEnabled:$false -MailNickname 'unused' -SecurityEnabled
if ($null -eq $grp)
{
return "Null received from New-MgGroup!"
}
else
{
return "Group {$_} added successfully."
}
}
}
while ($jobs.Completed -contains $False) {
Start-Sleep -Seconds 1
}
$jobs | Wait-RSJob | Receive-RSJobResult:
Sometimes when creating groups in parallel, a few requests fail with errors:
> $jobs | Wait-RSJob | Receive-RSJob
One or more errors occurred.
Null received from New-MgGroup!
Group 2 added successfully.
Group 3 added successfully.
Group 4 added successfully.
> $jobs
Id Name State HasMoreData HasErrors Command
-- ---- ----- ----------- --------- -------
117 Add group: {1} Completed True True ...
118 Add group: {2} Completed True False ...
119 Add group: {3} Completed True False ...
120 Add group: {4} Completed True False ...The exception message retrieved from the job object:
Message : Collection was modified; enumeration operation may not execute.
Data : {}
InnerException :
TargetSite : Void ThrowInvalidOperationException(System.ExceptionResource)
StackTrace : at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
at System.Collections.Generic.Dictionary`2.Enumerator.MoveNext()
at System.Net.Http.Headers.HttpHeaders.<GetEnumerator>d__20.MoveNext()
at Microsoft.Graph.PowerShell.HttpMessageLogFormatter.<CloneAsync>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Graph.PowerShell.HttpMessageLogFormatter.<GetHttpRequestLogAsync>d__1.MoveNext()
HelpLink :
Source : mscorlib
HResult : -2146233079The errors occur randomly - I once ran 100 parallel requests of which all succeed, and the other time I had 2 errors in 50 requests.
Should the Powershell Graph be considered as thread safe, or is multithreading not officially supported?
Update:
I was able to reproduce the same error using the built-in Start-Job | Wait-Job | Receive-Job commands.
I am however unable to reproduce this issue on Powershell 7.3, using neither Start-Job, nor ForEach-Object -Parallel.
Update 2:
While I initially reported that the issue is caused by parallel execution, I recently discovered that it randomly occurs during synchronous command calls as well.
The following code has a high probability of producing the exception mentioned above:
1..100 | ForEach-Object {
New-MgGroup -DisplayName "new-mggroup-test" -MailEnabled:$false -MailNickname 'unused'
}