C#如何将不仅仅是IAsyncResult传递给AsyncCallback?

时间:2011-04-11 18:06:52

标签: c# asynchronous httpwebrequest iasyncresult asynccallback

如何将不仅仅是IAsyncResult传递给AsyncCallback?

示例代码:

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

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

我想传递示例变量bool iWantInToo。我不知道如何将其添加到new AsyncCallback(iEndGetResponse)

1 个答案:

答案 0 :(得分:11)

你必须使用对象状态来传递它。现在,你传递了req参数 - 但是你可以传入一个包含它和布尔值的对象。 / p>

例如(使用.NET 4的元组 - 如果你在.NET< = 3.5,你可以使用自定义类或KeyValuePair,或类似的):

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