我正在尝试运行一项任务,但它似乎永远不会结束,卡住了。我通常会怀疑是无限循环,但这次没有循环。此代码在 Android 设备上以 xamarin 形式运行。
首先,这是最终锁定的任务。
public static async Task<InventoryItem> GetTaskInventory(string labeladresse)
{
InventoryItem result = null;
await Task.Run(() =>
{
try
{
IDeliveryService client = Common.GetDeliveryService();
result = client.GetLineTaskInventory(labeladresse);
}
catch (Exception ex)
{
LogError(ex);
}
finally
{
}
}).ConfigureAwait(false); ;
return result;
}
很简单,它调用一个服务(服务正在工作)并得到一些结果。
其次,这是调用它的部分(来自视图模型):
async Task ExecuteLoadItemsCommand()
{
[...]
else
{
IsBusy = true;
primaryBin.inventoryItem = await Common.GetTaskInventory(primaryBin.labelAdresse);
primaryBin.binContents = new List<BinContent>(primaryBin.inventoryItem._BinContent);
List<String> StockIds = new List<string>();
foreach (var bincontent in primaryBin.binContents)
{
StockIds.Add(bincontent.StockId);
}
primaryBin.productsinBinContent = new List<InventoryProduct>(await Common.GetInventoryProducts(new ProductSearchFilter { StockId = StockIds.ToArray() }));
primaryBin.productsinBinContent.Sort(delegate (InventoryProduct t1, InventoryProduct t2) { return (t1.ProductName.CompareTo(t2.ProductName)); });
foreach (var product in primaryBin.productsinBinContent)
{
var bincontent = primaryBin.binContents.Find(s => s.StockId == product.StockId);
var _item = new ListItem() { Name = product.ProductName, Id = bincontent.Id.ToString(), Quantity = bincontent.Quantity, BookedQuantity = bincontent.BookedQuantity, EAN = product.Ean, CodeSupplier = product.MainSupplier, showTransferButton = primaryBin.showTransferButton, showDeleteButton = primaryBin.showDeleteButton};
primaryBin.Items.Add(_item);
}
}
}
到目前为止一切顺利。调用函数,保存结果,根据内容填充列表显示。
这是视图模型的构造函数 公共 Inv2ViewModel
(int typePage, ListView primaryList, ListView secondaryList, BoxView selectBinBoxView, string title = "Move Goods")
{
Title = title;
IsPrimaryBin = true;
primaryBin = new BinDefinition(1,typePage);
secondaryBin = new BinDefinition(2, typePage);
primaryBin.Items = new ObservableCollection<ListItem>();
secondaryBin.Items = new ObservableCollection<ListItem>();
LoadItemsCommand = new Command(async () => Task.WaitAll(ExecuteLoadItemsCommand()));
SwitchBinCommand = new Command(async () => await ExecuteSwitchBinCommand());
this.primaryList = primaryList;
this.secondaryList = secondaryList;
this.selectBinBoxView = selectBinBoxView;
pageType = typePage;
isInit = true;
secondaryList.TranslateTo(DeviceDisplay.MainDisplayInfo.Width, 0, 1000);
LoadItemsCommand.Execute(true);
}
我的程序卡在 GetTaskInventory 中,就在“finally”之后,在我放置 .ConfigureAwait(false) 之前永远不会退出等待。然后它出去了,但现在它在返回后锁定。我不明白这是怎么回事。这些功能经常使用,但从未引起过问题。
感谢您的帮助。
答案 0 :(得分:1)
这是您的问题:
LoadItemsCommand = new Command(async () => Task.WaitAll(ExecuteLoadItemsCommand()));
You shouldn't block on asynchronous code; that can cause deadlocks。在这种情况下,代码使用 Task.WaitAll
进行阻塞,这会导致与更常见的 .Result
/.Wait()
阻塞样式相同的死锁。
首先,我建议使用 await
来解决这个问题:
LoadItemsCommand = new Command(async () => await ExecuteLoadItemsCommand());