取消令牌处置异常

时间:2019-04-17 19:09:08

标签: c# xamarin.forms

我的这段代码起初运行良好。但是,将其添加到我存储了重用方法的类中之后,它仍然会失败。捕获到的异常表明CancellationTokenSource已被释放。有人可以指出我正确的方向吗?

我曾尝试创建一个新客户端并将HTTPClient类的CancellationToken.None添加到PutAsync()方法,但由于CancellationTokenSource Disposed异常,它仍然失败。

public async void AddProduct(Product product)
    {
        string storeId = "";

        try
        {
            var storeData = JObject.Parse(Connect.Json).SelectToken("store").ToString();

            var stores = JsonConvert.DeserializeObject<List<Store>>(storeData);

            var store = stores[0];

            storeId = store.Id;

            store.Products.Add(product);

            ProdInfo info = new Info();

            foreach(Product p in store.Products)
            {
                info.AddedProducts =  + p.Id;
            }

            var content = JsonConvert.SerializeObject(info);

            using (Connect.Client)
            using (var response = await Connect.Client.PutAsync(_url + "/stores/" + storeId, new StringContent(content)))
            {
                var cont = response.Content;
                string result = await cont.ReadAsStringAsync();

                if ((int)response.StatusCode == 200)
                {
                    this.JobResult = result;
                    //this.JobResult = "Store has been successfully updated";
                }
                else
                {
                    this.JobResult = result;
                    //this.JobResult = "Store was not updated!";
                }
            }
        }
        catch (Exception ex)
        {
            //this.JobResult = "Store has not been updated due to an error.";
            this.JobResult = ex.Message;
        }
    }

1 个答案:

答案 0 :(得分:0)

我能够通过简单地从所有方法中删除“ using(Connect.Client)”来解决此问题。正如@sellotape所说,在我能够再次使用它之前,他们正在处置HttpClient。谢谢大家的贡献。