class A
{
public void B()
{
var request = HttpWebRequest("www.cnblogs.com");
request.BeginGetResponse(new AsyncCallback(RespCallback), request);
}
private void RespCallback(IAsyncResult ar)
{
HttpWebRequest req = rs.Request;
HttpWebResponse resp = (HttpWebResponse)req.EndGetResponse(ar);
Stream ResponseStream = resp.GetResponseStream();
.........
}
}
class B
{
}
问题是: 在类B中怎么获得类A中HttpWebRequest异步获得的ResponseStream?
你可以给A加个回调的属性或event,在RespCallback完成后调用,并将ResponseStream当参数传出去.
当其它类要得到ResponseStream时,只需要设置回调方法或event就可以了.
比如:
public class A {
public Action<System.IO.Stream> Callback { get; set; }
public void DoWork() {
System.IO.Stream stream = GetStreamMethod();
if (Callback != null) {
Callback(stream);
}
}
}
public class B {
public void Hello() {
A a = new A() { Callback = (stream) => {
//do...
} };
a.DoWork();
}
}