在更新计时器函数中更新文本block文本时,winui 3 cosxception错误
我正在尝试更新 textBlock
的文本。这是我的代码:
public static DateTime startTime;
System.Timers.Timer timer = new System.Timers.Timer(1000);
timer.AutoReset = true;
timer.Elapsed += Timer_Tick;
timer.Start();
private void Timer_Tick(object sender, EventArgs e)
{
timerLabel.Text = DateTime.Now.Subtract(startTime).ToString(@"hh\:mm\:ss");
}
当我运行它时,我会得到异常抛出:'System.Runtime.InterOpservices.comexception'winrt.runtime.dll
。我在该功能中输入的所有其他代码都将运行,它不会更新我的文本block的文本。
我还尝试了 system.threading.timer
并获得相同的错误。
我该如何解决此问题以更新文本屏幕的文本,每次播放第二次。我发现的每个答案似乎都无法与Winui 3一起使用。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
来自
system.timers
的计时器将在非UI线程上打勾,因此您必须使用 microsoft.ui.dispatching.dispatcherqueue 某种程度上。您可以在当前 window 或使用 dispatcherqueue.getforcurrentthread方法。
然后可以像这样编写您的代码:
请注意,您还可以使用 dispatcherqueue.createTimer方法它将在适当的线程中自动打勾。
A timer from
System.Timers
will tick on a non-UI thread, so you must use a Microsoft.UI.Dispatching.DispatcherQueue somehow.You can use the one on the current Window or get one from the current thread (if it has a dispatcher queue) using the DispatcherQueue.GetForCurrentThread method.
Then your code can be written like this:
Note that you can also use a timer provided by the DispatcherQueue itself with the DispatcherQueue.CreateTimer Method which will automatically tick in the proper thread.