我正在尝试开发我的第一个Xamarin应用程序。
我有两个webservices类: RestClient:它发出请求并获得:它应该获得json字符串并将其反序列化为Object。
我知道Wait方法不是最好的选择,但是我尝试了很多不同的建议版本,但是它不起作用。每次尝试都以僵局告终。每个线程都在后台工作。如何将我的数据返回到UI?
我的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();
}
}发布于 2017-07-24 07:29:57
Task.Run(loadSupplier).Wait();会解决你的问题。
您的死锁是由异步方法试图在调用方线程上执行延续造成的,但是调用方线程会被阻塞,直到该异步方法完成为止。
发布于 2017-07-23 20:36:10
.Wait()比“非最佳选项”更糟糕--它将在任何具有同步上下文的环境中主动导致循环等待。有关更多细节,请阅读这篇文章。
如果必须调用它以正确插入对象,则可以使用异步工厂方法或其他方法。
https://stackoverflow.com/questions/45269411
复制相似问题