問題:BeginGetResponse 異步回調 ResponseCallback 方法內獲取到 JsonSource,但外部調用類 B 無法直接獲取該值。
定義委托或回調接口,在異步完成時調用,將結果傳遞給調用方。
public class A {
public void SetJsonSource(string uri, Action onCompleted) {
WebRequest req = WebRequest.Create(uri);
req.Method = "GET";
req.BeginGetResponse(ar => {
try {
var response = req.EndGetResponse(ar);
using (var stream = response.GetResponseStream())
using (var reader = new StreamReader(stream)) {
string json = reader.ReadToEnd();
onCompleted?.Invoke(json); // 回調傳遞結果
}
} catch (Exception ex) {
onCompleted?.Invoke(null); // 或傳遞異常
}
}, req);
}
}
// 調用
public class B {
public void GetSource() {
var a = new A();
a.SetJsonSource("https://api.example.com", json => {
if (json != null) {
Console.WriteLine("收到 JSON: " + json);
// 後續處理...
}
});
}
}
public class A {
public async Task GetJsonSourceAsync(string uri) {
using (var client = new HttpClient()) { // 推薦 HttpClient
return await client.GetStringAsync(uri);
}
}
}
public class B {
public async void GetSource() {
var a = new A();
string json = await a.GetJsonSourceAsync("https://api.example.com");
Console.WriteLine(json);
}
}
HttpClient + async/await,代碼線性、異常處理自然、避免回調地獄。採用委托回調或 Task 包裝,即可在異步完成時獲取 JsonSource 並繼續業務流程。