1

I have a method

 private string MakeRequest

which has returned me a string earlier, but now I have in this method an async operation.

request.BeginGetRequestStream(GetRequestStreamCallback, request);

 private void GetRequestStreamCallback(IAsyncResult asynchronousResult)
    {
        var request = (HttpWebRequest)asynchronousResult.AsyncState;

        // End the operation
        var postStream = request.EndGetRequestStream(asynchronousResult);

        // Convert the string into a byte array.
        byte[] byteArray = Encoding.UTF8.GetBytes(request.Connection);

        // Write to the request stream.
        postStream.Write(byteArray, 0, request.Connection.Length);
        postStream.Close();

        // Start the asynchronous operation to get the response
        request.BeginGetResponse(GetResponseCallback, request);
    }

    private static void GetResponseCallback(IAsyncResult asynchronousResult)
    {
        var request = (HttpWebRequest)asynchronousResult.AsyncState;

        // End the operation
        var response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
        var streamResponse = response.GetResponseStream();
        using (var streamRead = new StreamReader(streamResponse))
        {
            var responseString = streamRead.ReadToEnd();
            var trimResponseString = responseString.Trim(); // I need this string to return from MakeRequest
            // Close the stream object
            streamResponse.Close();
            streamRead.Close();

            // Release the HttpWebResponse
            response.Close();
            allDone.Set();
        }
    }

How can I return the string from last callback to MakeRequest?

6
  • Have you considered using Tasks instead? WebRequest.GetRequestStreamAsync returns a Task, you can await that. Not sure what you are calling from but if its WPF, WinForms, asp.net your entry can be marked as async with return of some form of Task. You can then await the GetRequestStreamAsync Commented Mar 15, 2017 at 10:35
  • @Igor, how exactly should I do? I have never done it before. Commented Mar 15, 2017 at 10:36
  • What version of .NET are you using? There are much easier ways to do this nowadays. Commented Mar 15, 2017 at 10:41
  • @JLRishe .NET 4.5 Commented Mar 15, 2017 at 10:43
  • @Ekaterina - what is your entry point (ie. what are you calling this from)? Console app, wpf, winforms, mvc, asp.net, something else? Commented Mar 15, 2017 at 10:45

1 Answer 1

2

If you're using .NET 4.5, you can take advantage of the Task-based methods in WebRequest:

public async Task<string> MakeRequest()
{
    var request = WebRequest.Create(url);

    var postStream = await request.GetRequestStreamAsync();

    // Convert the string into a byte array.
    byte[] byteArray = Encoding.UTF8.GetBytes(request.Connection);

    // Write to the request stream.
    postStream.Write(byteArray, 0, request.Connection.Length);
    postStream.Close();

    var response = (HttpWebResponse)(await request.GetResponseAsync());
    var streamResponse = response.GetResponseStream();

    using (var streamRead = new StreamReader(streamResponse))
    {
        var responseString = streamRead.ReadToEnd();
        var trimResponseString = responseString.Trim(); // I need this string to return from MakeRequest
        // Close the stream object
        streamResponse.Close();
        streamRead.Close();

        // Release the HttpWebResponse
        response.Close();
        allDone.Set();

        return trimResponseString;
    }
}

If you're calling this from a context that isn't itself asynchronous, you can call this method and then synchronously await the result:

string result = MakeRequest().GetAwaiter().GetResult();
Sign up to request clarification or add additional context in comments.

2 Comments

But HttpWebResponse is not awaitable var response = await (HttpWebResponse)request.GetResponseAsync();
@Ekaterina Sorry, needed to rearrange the parentheses. Please see my update.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.