Device.StartTimer 在 MAUI 中已弃用,替代方案是什么?

Apq*_*pqu 18 maui

我正在尝试将 Xamarin.Forms 应用程序移植到 .NET MAUI,但遇到了 Device.StartTimer 的弃用,虽然这显然目前在 MAUI 中仍然有效,我有兴趣了解替代方案是什么?

目前我有一个包装类如下:

public void Start()
{
   if (IsRunning)
   {
      return;
   }
   var wrapper = new TaskWrapper(Task, IsRecurring, true);
   Tasks.Add(wrapper);
   Device.StartTimer(Interval, wrapper.RunTask);
}
Run Code Online (Sandbox Code Playgroud)

我尝试用System.Timers.Timer替换它,但这导致了由于位于错误的线程上而无法修改 UI 元素的问题?计时器包装器本身在多个地方使用,因此在这种情况下我也不能使用绑定。

实际上是否有 Device.StartTimer 的直接替代品?非常感谢任何帮助。

Jul*_*ian 32

设备计时器在 MAUI 中已过时。

\n

您可以创建一个 IDispatcherTimer 实例并订阅 Tick 事件,如下所示:

\n
var timer\xc2\xa0=\xc2\xa0Application.Current.Dispatcher.CreateTimer();\ntimer.Interval = TimeSpan.FromSeconds(1);\ntimer.Tick += (s,e) => DoSomething();\ntimer.Start();\n
Run Code Online (Sandbox Code Playgroud)\n

根据您使用计时器的上下文,您应该使用该MainThread.BeginInvokeOnMainThread()方法来更新 UI 元素,这在 iOS 上尤其重要:

\n
void DoSomething()\n{\n    MainThread.BeginInvokeOnMainThread(() =>\n    {\n        //Update view here\n    });\n}\n
Run Code Online (Sandbox Code Playgroud)\n

有关 UI 主线程的更多信息:

\n

https://learn.microsoft.com/en-us/dotnet/maui/platform-integration/appmodel/main-thread

\n


小智 13

IDispatcherTimer timer;

timer = Dispatcher.CreateTimer();
timer.Interval = TimeSpan.FromMilliseconds(1000);
timer.Tick += (s, e) =>
{
    label.Text = DateTime.Now.ToString();
};
timer.Start();
Run Code Online (Sandbox Code Playgroud)

https://learn.microsoft.com/en-us/dotnet/maui/user-interface/controls/button#press-and-release-the-button


小智 5

namespace Microsoft.Maui.Dispatching

    IDispatcherTimer timer4Registration;
    timer4Registration = Application.Current.Dispatcher.CreateTimer();
    timer4Registration.Interval = TimeSpan.FromSeconds(10);
    timer4Registration.Tick += (sender, e) => registerDeviceViaServer();
    timer4Registration.Start();enter code here
Run Code Online (Sandbox Code Playgroud)

这对我来说非常适合 .NET MAUI 框架