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

1

5

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).

Sunset answered 11/4, 2011 at 18:6 Comment(0)
J
12

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..
}
Jointworm answered 11/4, 2011 at 18:8 Comment(5)
Very very interesting. Testing this now. I've never seen this Tuple deal before, looks very useful!Sunset
Nobody sees this method ugly? There is supposed to be a better to pass parameters.Oregon
@Oregon this pattern, in general, has been replaced for async work. most newer apis work against Task <T>Jointworm
@ReedCopsey So modern way is to use "await" to let the callback finish and then do the job what previously "callback" did?Oregon
@Oregon Yes. await makes callbacks unnecessaryJointworm

© 2022 - 2024 — McMap. All rights reserved.