2 回答

TA貢獻(xiàn)1860條經(jīng)驗(yàn) 獲得超9個(gè)贊
考慮使用異步事件處理程序和靜態(tài)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;
}
使用這種模式可以幫助避免阻塞調(diào)用和套接字耗盡,這有時(shí)會(huì)導(dǎo)致死鎖,從而導(dǎo)致超時(shí)。

TA貢獻(xiàn)1765條經(jīng)驗(yàn) 獲得超5個(gè)贊
嘗試這個(gè)。
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 關(guān)注
- 251 瀏覽
添加回答
舉報(bào)