我在视图模型中有一个方法,每次从 Binance Api 发送数据时都会更新可观察集合(指标)。但是,如果我从该列表中删除最后一项(多次按下应用程序上的按钮,甚至在关键时刻按下一次),我可能会收到索引超出范围错误。仅当我捕获错误时,程序才会继续,但我一开始就无法找到避免错误的机制。
public MainViewModel()
{
//this command starts the Api stream from Binace.
UpdateAllCommand = new Command(async () => await this.UpdateAll());
//this command removes the last item from the list
RemoveIndicatorCommand = new Command(this.RemoveIndicator);
}
async Task UpdateAll()
{
var result = await this.socketClient.UsdFuturesApi.SubscribeToMiniTickerUpdatesAsync(this.Symbol, async data =>
{
//Update Indicators everytime data is streamed
if (this.Indicators != null && this.Indicators.Count > 0)
{
for (int i = 0; i < this.Indicators.Count; i++)
{
if (i < this.Indicators.Count)
{
try
{
var values = await GetIndicator(this.Indicators[i].Name, this.Indicators[i].Period);
this.Indicators[i].Value = values[^1];
}
catch (Exception ex)
{
...
}
}
}
}
});
}
}
void RemoveIndicator()
{
if (this.Indicators.Count > 0)
{
this.Indicators.RemoveAt(this.Indicators.Count - 1);
}
}
我知道,如果我尝试在更新和循环时从集合中删除项目,我可能会遇到索引超出范围错误。但我怎样才能安全地删除它而不出错呢?我尝试使用 lock 或 semaphoreslim 但没有结果。我的方法可能完全错误,但请帮助我提示。谢谢!
要尝试的一件事是使用
Linq
而不是索引来获取最后一项。
void RemoveIndicator()
{
if (Indicators.LastOrDefault() is MyIndicator removeMe)
{
Indicators.Remove(removeMe);
}
}
是的,你在这个街区周围放一把锁的直觉可能是个好主意。