【发布时间】:2020-09-15 16:45:04
【问题描述】:
我尝试使用并行线程不断刷新网格的内容。那是不工作的代码:
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 子句,但它没有初始化和显示新页面。
我认为这根本不是最佳做法,我想请教一下如何做得更好。
【问题讨论】:
-
你为什么要替换整个页面堆栈只是为了修改单个页面的内容?
-
因为只有创建视图的线程才能修改它。所以我不能打开一个新线程,它每 3 秒检查一次更改以及从这个线程访问“主”线程创建的视图。
-
非常感谢!
-
更新UI操作应该在主线程中执行。尝试将相关功能代码放在主线程中。如:
MainThread.BeginInvokeOnMainThread(() =>{// Code to run on the main thread});.
标签: android xamarin xamarin.forms cross-platform