title: When calling wininet functions random NullReferenceException occur
body: <p>Not sure why but at random when calling the function <code>InternetQueryDataAvailable</code> a null ref exception occurs for no apparent reason sins non of the arguments which it accepts can be null:</p>
  
  <pre><code>[DllImport(Dlls.Wininet, SetLastError = true)]
  public static extern bool InternetQueryDataAvailable([In] IntPtr hFile, [Out] out int numberOfBytesAvailable, [Optional, In] int reserved0, [Optional, In] IntPtr reserved1);
  </code></pre>
  
  <p>Here is the exception:</p>
  
  <p><a href="https://i.stack.imgur.com/mzv86.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mzv86.png" alt="enter image description here"></a></p>
  
  <p>And no, <code>CheckHandle()</code> isn't the culprit as all it does is check if <code>_handle</code> is zero or not, aka invalid.</p>
  
  <p>Also, if not this then after downloading all the data and attempting to close the application, sins I set it up so all the handles close before the app closes, the call to <code>InternetCloseHandle</code> throws the null ref exception even tho, just like with <code>InternetQueryDataAvailable</code>, non of the arguments are nullable sins all it accepts is a single <code>IntPtr</code>:</p>
  
  <pre><code>[DllImport(Dlls.Wininet, SetLastError = true)]
  public static extern bool InternetCloseHandle([In] IntPtr hInternet);
  </code></pre>
  
  <p>Am not sure what's going on because, on rare occasions everything works fine and I am able to download all the data and close the handle without a random exception being thrown.</p>
  
  <p>For those wondering what the function with InternetCloseHandle looks like, it's just:</p>
  
  <pre><code>public void Dispose()
  {
      if (_handle != IntPtr.Zero)
      {
          if (!WinINet.InternetCloseHandle(_handle))
          {
              throw new Win32Exception();
          }
          _handle = IntPtr.Zero;
      }
  
  }
  </code></pre>
  
  <p>Note that the exception which is thrown after calling <code>InternetQueryDataAvailable</code> only occurs after the first call, so the first is fine but all the ones after have a chance of triggering the exception.</p>