title: GetLastError race in Asynchronous Procedure Call
body: <p>Say I am using an APC where the procedure and the calling code both use SetLastError and GetLastError. This is resulting in unpredictable values from GetLastError. Is there any way out of this ?</p>
  
  <pre><code>VOID CALLBACK MyFunction(ULONG_PTR param)
  {
  
      SetLastError(1);
      // Doing some stuff here which takes some time
      // Expecting 1 but can I/should I get 0 here ?
      printf("LastError: %d\n", GetLastError());    
  }
  
  int APCtry()
  {
  
      SetLastError(0);
  
      DWORD dummy = 0;
  
      if (!QueueUserAPC(MyFunction, GetCurrentThread(), dummy))
      {
          return 0;
      }      
  
      printf("LastError: %d\n", GetLastError());
  
      SleepEx(100, TRUE);
  
      //SetLastError(0); Edited and commented
  
      printf("LastError: %d\n", GetLastError());
  
      return 0;
  }
  </code></pre>