title: Problems with accessing MainModule too early.. (C#)
body: <p>Okay so here's the long and short of it, and it's a problem that's been plaguing me for awhile now. I've written something that launches a game process, then in order to proceed with what the application does (it's for modding purposes) it needs to suspend the process and access the MainModule for retrieving the BaseAddress of the process - unfortunately this seems to &quot;sometimes&quot; but not always cause a Win32 Exception, presumably because MainModule is being accessed too early. (However for the purposes of the tool I'm writing, I need to access this as early as possible to apply game fixes before bootup proceeds too far..)</p>
  <pre><code>Process game = Process.Start(installPath + &quot;game.exe&quot;, launchCommands);
  
              while (true) { if (game.MainModule != null) { game.Suspend(); break; } }
  
              int processId = game.Id;
              IntPtr baseAddress = game.MainModule.BaseAddress;
  </code></pre>
  <p>This is the current code I'm using, I originally thought that checking whether MainModule was null or not would avoid the entire problem (and in fact I haven't personally encountered it since writing this in) but one of my testers will sometimes hit a Win32Exception on the if statement..</p>
  <p>Without the if statement and while loop, if I just suspend the process outright the same exception will occur anyway when it reaches baseAddress, for much the same problem as near as I can tell.. In a much earlier iteration of my code I did this:</p>
  <pre><code>public static IntPtr BaseAddrScan(int processId, ProcessLauncher process)
      {
          try 
          {
              IntPtr baseAddress = Process.GetProcessById(processId).MainModule.BaseAddress;
              return baseAddress;
          }
          catch
          {
              Process.GetProcessById(processId).Resume();
              System.Threading.Thread.Sleep(1);
              Process.GetProcessById(processId).Suspend();
              return BaseAddrScan(processId, process);
          }
      }
  </code></pre>
  <p>Effectively it tries to scan for the BaseAddress, and if it hits the exception it goes to the catch block that resumes the (previously) suspended process, waits a tick, then suspends it again and loops back in on itself and tries to do everything again, hopefully <em>eventually</em> edging closer to a point where it can access MainModule and all is well.. And I mean.. Yes this <em>worked</em>, but this seems horrible a &quot;solution&quot; to this problem, it feels like a nasty abuse of try\catch and just clumsy coding all and all. Surely there has to be some way to do a loop until MainModule is ready without causing an exception..?</p>
  <p><a href="https://i.stack.imgur.com/pfBL5.png" rel="nofollow noreferrer">Exception from Event Viewer</a></p>