How to call AsyncCallback with a parameter in an BeginGetRequestStream (C#)

1.2k views Asked by At
    public void SendPost(string code)
    {
        // Create the web request object
        HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(Resource.Url);
        webRequest.Method = "POST";
        webRequest.ContentType = "application/x-www-form-urlencoded";

        //Start the request
        webRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), webRequest);
    }

I want to call the GetRequestStreamCallback with an parameter.

Does anyone know how to do this?

2

There are 2 answers

0
Haukinger On BEST ANSWER

Use a lambda instead of a method group.

That is:

webRequest.BeginGetRequestStream(new AsyncCallback(result => GetRequestStreamCallback(result, someParameter)), webRequest);
0
Panagiotis Kanavos On

Instead of BeginGetRequestStream, use GetRequestStreamAsync. With it, you can use the async/await keywords to await for an operation to complete asynchronously and continue execution :

public async Task SendPost(string code)
{
    // Create the web request object
    HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(Resource.Url);
    webRequest.Method = "POST";
    webRequest.ContentType = "application/x-www-form-urlencoded";

    //Start the request
    var stream=await webRequest.GetRequestStream(webRequest);
    MyStreamProcessingMethod(stream);
    ...
}

GetRequestStreamAsync and async/await are available in all supported .NET versions.