title: PowerShell - Singleton - usage in a runspace - runspace hangs
body: <p><strong>Given</strong>:</p>
  
  <ul>
  <li>Using PowerShell 5.1</li>
  <li>A powershell script that runs successful on the console</li>
  <li>using multiple includes/modules and oop classes.</li>
  <li>using singleton classes</li>
  </ul>
  
  <p><strong>When</strong>:</p>
  
  <ul>
  <li>running in a runspace.</li>
  </ul>
  
  <pre><code>          $rs = [runspacefactory]::CreateRunspace()
            $PowerShell = [powershell]::Create()
            $PowerShell.runspace = $rs
            $rs.Open()
            [void]$PowerShell.AddScript(&lt;script ps1 file&gt;)
            [void]$PowerShell.AddArgument(&lt;param x&gt;)
            $PowerShell.Invoke()
  </code></pre>
  
  <ul>
  <li>debugging the runspace </li>
  </ul>
  
  <p><strong>Then</strong>:</p>
  
  <ol>
  <li>the runspace hangs at a code statement where
  
  <ul>
  <li>the singleton is addressed</li>
  <li>a method of the singleton is addressed to alter one of its properties</li>
  </ul></li>
  </ol>
  
  <p><strong>My goal</strong>:</p>
  
  <p>To execute multiple script files in parallel</p>
  
  <p><strong>My questions</strong>:</p>
  
  <ul>
  <li>Why may it potentially fail in the 1st place? Has it something to do with thread safety? If so; how can I try to resolve it..</li>
  <li>Is there a best practice for using singletons (with the ability to alter property states) throughout runspaces?</li>
  </ul>
  
  <pre><code>class Singleton {
  
      hidden static [Singleton] $_instance = [Singleton]::new()
  
      static [Singleton] $Instance = [Singleton]::GetInstance()
  
      [Guid] $SingletonTarget = [Guid]::NewGuid()
  
      hidden Singleton() {
      }
  
      hidden static [Singleton] GetInstance() {
          return [Singleton]::_instance
      }
  }
  </code></pre>
  
  <p>Source: <a href="https://gist.github.com/guitarrapc/2fde990d166286459c309b7cab03938b" rel="nofollow noreferrer">https://gist.github.com/guitarrapc/2fde990d166286459c309b7cab03938b</a></p>