我尝试使用并行线程连续刷新网格的内容。多数民众赞成在代码不起作用:
private void ContiniouslyRefreshPage(int interval)
{
var startTimeSpan = TimeSpan.Zero;
var periodTimeSpan = TimeSpan.FromSeconds(interval);
Dictionary<string, string> lastCheck = bluetoothService.CheckRequirements();
var timer = new System.Threading.Timer((e) =>
{
Dictionary<string, string> newCheck = bluetoothService.CheckRequirements();
if (!(lastCheck.Count == newCheck.Count && !bluetoothService.CheckRequirements().Except(lastCheck).Any()))
{
Application.Current.MainPage = new MasterDetail
{
Detail = new NavigationPage(new TestingPage())
{
BarBackgroundColor = Color.White,
BarTextColor = Color.Black
}
};
lastCheck = newCheck;
}
}, null, startTimeSpan, periodTimeSpan);
}
if子句起作用,因此仅当我的数据集发生更改时页面才刷新(数据集由CheckRequirements-Method返回)
代码不起作用:发生更改时,它会进入if子句,但不会初始化并显示新的Page。
我认为这根本不是最佳实践,我想征询如何做得更好的建议。
更新的UI操作应在主线程中执行。尝试将相关的功能代码放入主线程。如:
private void ContiniouslyRefreshPage(int interval)
{
...
MainThread.BeginInvokeOnMainThread(() =>
{
Application.Current.MainPage = new MasterDetail
{
Detail = new NavigationPage(new TestingPage())
{
BarBackgroundColor = Color.White,
BarTextColor = Color.Black
}
};
};
}