在更新计时器函数中更新文本block文本时,winui 3 cosxception错误

发布于 2025-02-09 10:06:04 字数 625 浏览 2 评论 0 原文

我正在尝试更新 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一起使用。

I'm trying to update the Text of a TextBlock every time a timer fires. Here is my code:

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");
}

When I run it I get Exception thrown: 'System.Runtime.InteropServices.COMException' in WinRT.Runtime.dll. All other code I put in that function will run, it just won't update the text of my TextBlock.
I've also tried with a System.Threading.Timer and get the same error.

How can I fix this to update the Text of my TextBlock every time a second elapses? Every answer I find doesn't seem to work with WinUI 3.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

伏妖词 2025-02-16 10:06:04

来自 system.timers 的计时器将在非UI线程上打勾,因此您必须使用 microsoft.ui.dispatching.dispatcherqueue 某种程度上。

您可以在当前 window 或使用 dispatcherqueue.getforcurrentthread方法

然后可以像这样编写您的代码:

private void Timer_Tick(object sender, EventArgs e) => DispatcherQueue.TryEnqueue(() =>
{
    timerLabel.Text = DateTime.Now.Subtract(startTime).ToString(@"hh\:mm\:ss");
});

请注意,您还可以使用 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:

private void Timer_Tick(object sender, EventArgs e) => DispatcherQueue.TryEnqueue(() =>
{
    timerLabel.Text = DateTime.Now.Subtract(startTime).ToString(@"hh\:mm\:ss");
});

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文