0

I have the problem that a synchronous HttpWebRequest get stucked after disabling the network connection. It will not return unless i use the debugger. For your interest i am not able to use asynchronous HttpWebRequest because the requests have to be handled recursively.

This method is called from a thread:

private void DoWork()
{
    ...
    HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
    httpWebRequest.Method = WebRequestMethods.Http.Get;
    var response = (HttpWebResponse)request.GetResponse();
    ...
}

Thread starting:

var workerThread = new Thread(DoWork)
{
    IsBackground = true
};
workerThread.Start();

GetResponse is never returning.

Is there a way to cancel the request if i recognize that the network connection got lost or have do i have to live with the problem until we found a asynchronous solution?

Action Heinz
  • 722
  • 10
  • 23
  • How exactly are you making that synchronous call? Are you using a Task, or are using await? A code sample would be nice. –  Oct 25 '22 at 17:19
  • Since you are using a Thread you can use `workerThread.Abort()` which is a rather dirty way to kill your thread. Take a look at this [discussion](https://stackoverflow.com/questions/3632149/question-about-terminating-a-thread-cleanly-in-net) for 'clean' Thread killing. I recommend using the [GetResponseAsync()](https://learn.microsoft.com/de-de/dotnet/api/system.net.httpwebrequest.abort?view=net-6.0) method though... you can simply call `Request.Abort()` on the async version. –  Oct 26 '22 at 08:59

0 Answers0