TaskFactory.FromAsync with BeginGetRequestStream/EndGetRequestStream hangs

后端 未结 1 1067
难免孤独
难免孤独 2020-12-25 09:26

I have a method like this, that hangs when declaring responseObject using Task.Factory.FromAsync()

private async Task post(string          


        
相关标签:
1条回答
  • 2020-12-25 09:39

    First of all: Don't use ".Result" in async methods. This will block the thread that is running your method. Use "await" instead, so the thread jumps back to your method when the result is acquired.

    The problem with your code is that you open a request stream, but you never close it. So when should it expect to finish your request and send it? It'll always expect more input to come, until the request runs in a timeout. Also you have not set a content-type and content-length.

    private async Task<string> post(string url, string postdata)
        {
            var request = WebRequest.Create(new Uri(url)) as HttpWebRequest;
            request.Method = "POST";
    
            byte[] data = Encoding.UTF8.GetBytes(postdata);
            request.ContentLength = data.Length;
    
            using (var requestStream = await Task<Stream>.Factory.FromAsync(request.BeginGetRequestStream, request.EndGetRequestStream, request))
            {
                await requestStream.WriteAsync(data, 0, data.Length);
            }
    
    
            WebResponse responseObject = await Task<WebResponse>.Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, request);
            var responseStream = responseObject.GetResponseStream();
            var sr = new StreamReader(responseStream);
            string received = await sr.ReadToEndAsync();
    
            return received;
    }
    
    0 讨论(0)
提交回复
热议问题