开发者

Passing custom value with request to use in BeginGetResponse callback

I have a situation where I need to send a custom value with a web request so I c开发者_运维百科an use it in the response my application receives. As my application may be sending multiple requests out I am using BeginGetResponse to send out each request asynchronously.

At the moment I am caching the value using a private variable and then accessing it in the callback method. I know this is asking for trouble because if the same method is invoked before I have gotten a response back from the previous request then the data could have been changed.

What I need to know is what is the best (standard) way to pass data in a request to process it in the response? My initial thought was a custom header but I am not sure...

Here is my code at the minute:

public void SendRequestAsnyc(string param1, string param2, string uri, int id)
{
    NameValueCollection @params = System.Web.HttpUtility.ParseQueryString(String.Empty);
    @params.Add("param1", param1);
    @params.Add("param2", param2);          
    byte[] data = UTF8Encoding.UTF8.GetBytes(@params.ToString());
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);        
    request.Method = WebRequestMethods.Http.Post;
    request.ContentLength = data.Length;
    request.ContentType = "application/x-www-form-urlencoded";
    var stream = request.GetRequestStream();
    stream.Write(data, 0, data.Length);
    // take a note of data to be processed in the callback
    _cachedId = id;    
    IAsyncResult ar = request.BeginGetResponse(new AsyncCallback(GetAsyncResponse), request);
}

private void GetAsyncResponse(IAsyncResult result)
{
    HttpWebRequest request = (HttpWebRequest)result.AsyncState;
    if (request.HaveResponse)
    {                
        var response = (HttpWebResponse)request.EndGetResponse(result);
        var reader = new System.IO.StreamReader(response.GetResponseStream());
        var data = reader.ReadToEnd();
        // process data
        // use _cachedId here to update database with response
    }
}


You need to create a new object that contains the request and the id. In previous versions of C#, you could do that with an array of objects or possibly an anonymous object. Here's how you would do it with an array of objects:

IAsyncResult ar = request.BeginGetResponse(GetAsyncResponse, new object[] {request, id});

private void GetAsyncResponse(IAsyncResult result)
{
    object[] params = (object[])result.AsyncState;
    HttpWebRequest request = (HttpWebRequest)params[0];
    int id = (int)params[1];
    // process here
}

With C# 4.0, you could use a Tuple<HttpWebRequest, int>.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜