Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在Xamarin PLC中不断更新用户界面_C#_Multithreading_User Interface_Xamarin - Fatal编程技术网

C# 在Xamarin PLC中不断更新用户界面

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

我的问题是在我的Xamarin PLC项目中不断更新我的UI。我第一次尝试使用线程(
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
    });

与面临问题的社区共享代码。