我正在尝试开发我的第一个Xamarin应用程序。
我有两个webservices类: RestClient:发出请求并获取json String Helper Class:应该获取Json String并将其反序列化为Object Type。
我知道Wait
方法不是最佳选择,但我尝试了很多不同的建议版本,但它不起作用。每次尝试都以死锁结束。每个线程都在后台运行。如何将我的数据恢复到用户界面?
我的RestClient类的代码:
class RestClient
{
public static string base_url = @"our Restservice address";
// public string completeUrl { get; set; }
HttpClient client;
public RestClient()
{
client = new HttpClient();
client.BaseAddress = new Uri(base_url);
//client.MaxResponseContentBufferSize = 256000;
}
public async Task<String> GetData(string endpoint)
{
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync(endpoint);
if (response.IsSuccessStatusCode)
{
string result = await response.Content.ReadAsStringAsync();
return result;
}
else
{
return null;
}
}
我的助手类代码
public SupplierHelper()
{
}
public async Task<Suppliers> getData()
{
RestClient restClient = new RestClient();
string result = await restClient.GetData("suppliers/13");
return JsonConvert.DeserializeObject<Suppliers>(result);
}
我的VievModelClass代码
public class AccountViewModel : BaseViewModel
{
public static SupplierHelper supHelper;
public static Suppliers sup;
public string Name { set; get; }
public string Address { set; get; }
public AccountViewModel()
{
loadSupplier().Wait();
}
public async Task loadSupplier()
{
supHelper = new SupplierHelper();
sup = await supHelper.getData();
}
}
答案 0 :(得分:0)
.Wait()
比#34更糟糕,而不是最好的选择&#34; - 它会在具有同步上下文的任何环境中主动导致循环等待。请阅读this article了解详情。
如果必须调用它来正确初始化对象,则可以使用异步工厂方法等。
答案 1 :(得分:0)
Task.Run(loadSupplier).Wait();
将解决您的问题
您的死锁是由尝试在调用程序线程上执行延续的异步方法引起的,但调用程序线程被阻塞,直到该异步方法完成。