Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# How do I pass more than just IAsyncResult into AsyncCallback?

How do I pass more than just the IAsyncResult into AsyncCallback?

Example code:

//Usage
var req = (HttpWebRequest)iAreq;
req.BeginGetResponse(new AsyncCallback(iEndGetResponse), req);

//Method
private void iEndGetResponse(IAsyncResult iA, bool iWantInToo) { /*...*/ }

I would like to pass in example variable bool iWantInToo. I don't know how to add that to new AsyncCallback(iEndGetResponse).

like image 261
PiZzL3 Avatar asked Apr 11 '11 18:04

PiZzL3


1 Answers

You have to use the object state to pass it in. Right now, you're passing in the req parameter - but you can, instead, pass in an object containing both it and the boolean value.

For example (using .NET 4's Tuple - if you're in .NET <=3.5, you can use a custom class or KeyValuePair, or similar):

var req = (HttpWebRequest)iAreq;
bool iWantInToo = true;
req.BeginGetResponse(new AsyncCallback(iEndGetResponse), Tuple.Create(req, iWantInToo));

//Method
private void iEndGetResponse(IAsyncResult iA) 
{
    Tuple<HttpWebRequest, bool> state = (Tuple<HttpWebRequest, bool>)iA.AsyncState;
    bool iWantInToo = state.Item2;

    // use values..
}
like image 76
Reed Copsey Avatar answered Sep 29 '22 23:09

Reed Copsey