C# 在Xamarin PLC中不断更新用户界面
我的问题是在我的Xamarin PLC项目中不断更新我的UI。我第一次尝试使用线程(C# 在Xamarin PLC中不断更新用户界面,c#,multithreading,user-interface,xamarin,C#,Multithreading,User Interface,Xamarin,我的问题是在我的Xamarin PLC项目中不断更新我的UI。我第一次尝试使用线程(System.Threading.Thread),但是这个选项在可移植类上不可用(我也想到了BackgroundWorker,但我认为它也不可用)。更新的内容来自一个HTTP请求,因此我必须使用async。我的下一步是使用任务,但我不明白。因此,我需要一种在显示页面时每秒运行一次异步方法的方法。 我该怎么做呢?这很容易 private async Task DoWork() { while(!stop
System.Threading.Thread
),但是这个选项在可移植类上不可用(我也想到了BackgroundWorker
,但我认为它也不可用)。更新的内容来自一个HTTP请求
,因此我必须使用async。我的下一步是使用任务,但我不明白。因此,我需要一种在显示页面时每秒运行一次异步方法的方法。
我该怎么做呢?这很容易
private async Task DoWork()
{
while(!stoppped)
{
await YourFunction();
await Task.Delay(1000);
}
}
stopped
只是一个类变量,可用于取消该函数。稍后,您可以查看CancellationTokens
和CancellationTokenSource
以更复杂的取消机制替换stopped
变量
如果您有一个使用线程的非常复杂的逻辑,那么您可以将PCL转换为.netstandard 2.0项目。此新库类型支持这些功能。如果将共享代码放在
NetStandard
而不是PCL
中,则可以使用System.Threading.Timer
。示例代码是:
Device.StartTimer(TimeSpan.FromSeconds(1), () =>
{
Task.Run(async () =>
{
await YourFunction;
});
return true; // True = Repeat again, False = Stop the timer
});
与面临问题的社区共享代码。