我开始在我的MacBook专业版上使用Xamarin Studio进行Xamarin.Forms开发。我构建了一个应用程序,其目的是查询PrestaShop网站,检索产品并展示它们。
在将应用程序部署到Android时,我在低于棉花糖的版本中遇到了一些问题,但我解决了它们,所以我不在这里描述它们。
在将应用程序部署到iOS (模拟器)时,我仍然有一个严重的问题。应用程序运行了,但是当我单击按钮检索数据时,它崩溃了,给出了一个System.ObjectDisposedException,它的消息是"The CancellationTokenSource has me disposed“。我会在这里粘贴相关的源代码:
async void button1_Click(object sender, System.EventArgs e)
{
try
{
HttpClientHandler hnd = new HttpClientHandler();
hnd.Credentials = new NetworkCredential("[apikey]", "");
string res;
using (var client = new HttpClient(hnd))
{
var responseText = await client.GetStringAsync("[endpoint]/products");
using (MemoryStream stream = new MemoryStream())
using (StreamWriter writer = new StreamWriter(stream))
{
writer.Write(responseText.Replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n", string.Empty));
writer.Flush();
stream.Position = 0;
XDocument doc = XDocument.Load(stream);
res = JsonConvert.SerializeXNode(doc, Formatting.Indented, true);
}
var data = JsonConvert.DeserializeObject<Dictionary<string, object>>(res);
//Result.Text = data["products"].GetType().ToString() + Result.Text;
Func<string, Task> creator_method = async (string id) =>
{
try
{
var responseProd = await client.GetStringAsync($"[endpoint]/products/{id}"); // AT THIS ROW THE EXCEPTION IS RAISED!!!
using (MemoryStream stream = new MemoryStream())
using (StreamWriter writer = new StreamWriter(stream))
{
writer.Write(responseProd.Replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n", string.Empty));
writer.Flush();
stream.Position = 0;
XDocument doc = XDocument.Load(stream);
res = JsonConvert.SerializeXNode(doc, Formatting.Indented, true);
}
var product_rawData = JsonConvert.DeserializeObject<Dictionary<string, object>>(res);
var productData = (JObject)product_rawData["product"];
try
{
views.Children.Add(new ProductXaml(productData["name"]["language"]["#cdata-section"].ToString(), float.Parse(productData["price"]["#cdata-section"].ToString().Replace('.', ',')), productData["id_default_image"]["@xlink:href"].ToString()));
}
catch (NullReferenceException nre)
{
views.Children.Add(new ProductXaml(productData["name"]["language"]["#cdata-section"].ToString(), float.Parse(productData["price"]["#cdata-section"].ToString().Replace('.', ',')), ""));
}
}
catch (Exception gex) { throw; }
};
foreach (var product in ((JObject)data["products"])["product"])
try
{
Device.BeginInvokeOnMainThread(async () => { await creator_method.Invoke(product["@id"].ToString()); });
}
catch (TaskCanceledException tce) { continue; }
catch (WebException we) { continue;}
}
}
catch (HttpRequestException ex)
{
Result.Text = ex.Message;
}
}我该如何解决这个问题呢?
发布于 2018-02-28 14:45:54
我也遇到了同样的问题,我对所有的api请求都使用了一个httpclient。
private static HttpClient httpClient;
public static HttpClient GetHttpClient()
{
if (httpClient == null)
{
httpClient = new HttpClient()
{
BaseAddress = new Uri(BaseUrl)
};
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
}
return httpClient;
}似乎您使用的(var client =HttpClient())...的CancellationToken已被第一个client.GetStringAsync()调用消耗。
Geoff的回答是:我删除了我的静态httpclient,现在为所有请求创建了一个新的httpclient,it's fixed my issue。
public static HttpClient GetHttpClient()
{
HttpClient httpClient = new HttpClient()
{
BaseAddress = new Uri(BaseUrl)
};
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
return httpClient;
}https://stackoverflow.com/questions/38010374
复制相似问题