WinHTTP Questions – async close on a sync request

Hello, my name is Deepak and I’m a SDET in serviceability. We handle a bunch of questions from developers using WinHTTP, and thought we might share then in a new posting series, “WinHTTP Questions”.

Can I cancel a synchronous WinHttpSendRequest call by closing the request handle from a different thread? Or, are there any requirements that I need to use the asynchronous WinHttpSendRequest if I need the ability to cancel it?

The short answer is don’t do that.

Let’s think about the implications of this proposed code. Thread 1 starts a synchronous request and Thread 2 comes along an issues a close. We can’t synchronize between Thread 1 and Thread 2 by definition because Thread 1’s call is synchronous, we either can deterministically call the close before the request call starts or after the call is completed. So to close the handle during the call results in a race condition. If thread 2 attempts to close the connection during the call, the handle passed in to WinHttpSendRequest may become invalid before WinHttp has a chance to work with it. While you might get lucky, you might also non-deterministically get a crash or memory corruption.

  — Deepak and Ari

Comments (2)

  1. Koby Kahane says:

    While you’re on the topic of WinHTTP questions, could you address whether the WinHTTP performance issue I describe at will be mitigated in the future?

    It appears you understand the limitations and behavior of the api (although you probably want ResponseBody, not ResponseText, since ResponseText does additional codepage related manipulation). First, I would urge that you file a suggestion on our connect site at (you need a live id and to “apply” for the program to submit feedback at ). Although I will note that the development priorities this time around will make it difficult to get to COM related winhttp use. Second, I would suggest using the apis via powershell for this usage. — Ari
  2. Anyang Ren says:

    Hi Deepak and Ari,

    The WinHttpCloseHandle page on MSDN says:

       An application can terminate an in-progress

       synchronous or asynchronous request by closing

       the HINTERNET request handle using


    This contradicts what you said in this posting.  If the MSDN page is wrong, could you please have it updated with your answer above?

    How do I cancel a synchronous WinHttpSendRequest call?

    It is legit to call cancel during the synchronous call once you’ve seen some sort of callback on the request. That get’s you around the race condition because you now know that the handle has been dereferenced correctly.