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

十年热恋 提交于 2019-12-05 00:42:29

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/5625501/c-sharp-how-do-i-pass-more-than-just-iasyncresult-into-asynccallback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!