2 回答

TA貢獻1860條經驗 獲得超9個贊
考慮使用異步事件處理程序和靜態HttpClient
static HttpClient client = new HttpClient();
public MainPage() {
InitializeComponent();
loadingData += onLoadingData;
}
protected override void OnAppearing() {
//loadingData -= onLoadingData; //(optional)
loadingData(this, EventArgs.Empty);
base.OnAppearing();
}
private event EventHandler loadingData = delegate { };
private async void onLoadingData(object sender, EventArgs args) {
var model = await GetPatientData();
this.BindingContext = new PatientViewModel(model);
}
public async Task<PatientModel> GetPatientData() {
PatientModel patient = null;
try {
Uri weburl = new Uri("myuri");
Console.WriteLine("a");
var response = await client.GetAsync(weburl);
Console.WriteLine("b");
if (response.IsSuccessStatusCode) {
Console.WriteLine("in");
patient = await response.Content.ReadAsAsync<PatientModel>();
Console.WriteLine("in funciton");
}
}catch(Exception ex) {
Console.WriteLine(ex);
}
return patient;
}
使用這種模式可以幫助避免阻塞調用和套接字耗盡,這有時會導致死鎖,從而導致超時。

TA貢獻1765條經驗 獲得超5個贊
嘗試這個。
public PatientModel abc { get; set; }
public MainPage()
{
InitializeComponent();
Bridge();
// Using abc
}
public async void Bridge()
{
abc = new PatientModel();
abc = await GetPatientData();
}
public async Task<PatientModel> GetPatientData()
{
PatientModel patient = null;
try
{
Uri weburl = new Uri("myuri");
HttpClient client = new HttpClient();
Console.WriteLine("a");
HttpResponseMessage response = await client.GetAsync(weburl);
Console.WriteLine("b");
if (response.IsSuccessStatusCode)
{
Console.WriteLine("in");
patient = await response.Content.ReadAsAsync<PatientModel>();
Console.WriteLine("in funciton");
return patient;
}
return patient;
}catch(Exception ex)
{
Console.WriteLine(ex);
return patient;
}
- 2 回答
- 0 關注
- 248 瀏覽
添加回答
舉報