K
K
kurai_maid2020-01-31 13:56:26
.NET
kurai_maid, 2020-01-31 13:56:26

WebResponse hangs, how to fix?

public static async Task<string> POST(string url, string postfields)
        {
            WebRequest request = WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.Timeout = 5000;
            byte[] parameters = System.Text.Encoding.UTF8.GetBytes(postfields);
            string res = null;
            request.ContentLength = parameters.Length;

            using(Stream stream = request.GetRequestStream())
            {
                stream.Write(parameters, 0, parameters.Length);
            }

            using (WebResponse response = await request.GetResponseAsync())
            {
                using (Stream stream = response.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        res = reader.ReadToEnd();
                    }
                }
            }
            return res;
        }


The program freezes when executing WebResponse response = await request.GetResponseAsync()
Changing timeouts or removing "using" and doing request.Abort() response.Close() does not help

UPD1: Just tried the code in dotnetfiddle.net - everything works. But I'm using .NET 4.8 and it's 4.7.2 - could this be a bug?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
BasiC2k, 2020-01-31
@kurai_maid

Move the procedure to a separate thread.
When the answer to your request comes, no one knows, so for the rest of the logic to work, your application will not need to wait for a response.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question