title: Write to location access violation, variable shared between threads
body: <p>I'm building an Unity application that makes some use of Selenium webdriver, I start the headless browser(chromedriver) in another Thread. In that thread I keep taking screenshots of what is shown in the headless browser, and store it in an byte array.
  In the main thread I have to use that byte array to make an image that Unity understands(Texture2D).
  I start the application, it works for a little while, but after some time has passed the application crashes. The crash file says:</p>
  <blockquote>
  <p>UnityPlayer.dll caused an Access Violation (0xc0000005) in module
  UnityPlayer.dll at 0023:105311be.</p>
  <p>Error occurred at 2020-07-30_150418.
  C:\Codes\Apps\MyApp\MyApp.exe, run by Fabio.</p>
  <p>94% memory in use.</p>
  <p>0 MB physical memory [423 MB free].</p>
  <p>0 MB paging file [1990 MB free].</p>
  <p>0 MB user address space [108 MB free].</p>
  <p>Write to location 007e7200 caused an access violation.</p>
  </blockquote>
  <p>second thread and the method &quot;LoadImage&quot;(as Coroutine) are started as soon as the application starts()</p>
  <p>code that take the screenshot:</p>
  <pre><code>public async Task ScreenShotBrowser()
      {
          //await Task.Yield();
          while (isBrowserOpen)
          {
                  Screenshot screenshot = ssdriver.GetScreenshot();  //Selenium stuff
              lock (imgArray)
              {
                  imgArray = screenshot.AsByteArray;               
              }
              Thread.Sleep(100);
          }
          
      }
  </code></pre>
  <p>loads the image to into the unity material:</p>
  <pre><code>IEnumerator LoadImage()
      {
          while (!isBrowserOpen) { yield return new WaitForSecondsRealtime(0.1f); } // ugly code, but avoid freezing
  
          while (isBrowserOpen)
          {
              
              lock (imgArray)
              {
                  mat.mainTexture = loadTexture(imgArray);
              }
              yield return new WaitForSecondsRealtime(0.1f); 
          }
      }
  
      private Texture2D loadTexture(byte[] imageArray)
      {
              Texture2D tex = new Texture2D(1, 1);
          lock (imageArray)
          {
              tex.LoadImage(imageArray);
          }
          return tex;
      }
  </code></pre>
  <p>thanks in advance</p>