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.

推荐答案

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.

Csharp相关问答推荐

等待限制选项似乎不适用于频道

ListaryImportProperty的默认DllImportSearchPathsProperty行为

EF Core判断是否应用了AsSplitQuery()

有没有一种方法可以在包含混合文本的标签中嵌入超链接?

使用LINQ to XML获取元素值列表是不起作用的

Quartz调度程序不调用作业(job)类

如何在实体框架中添加包含列表?

如何将MongoDB序列化程序设置为内部对象属性

在EF Core中,有没有什么方法可以防止在查询中写入相同的条件,而代之以表达式?

用于管理System.Text.Json中的多态反序列化的自定义TypeInfoResolver

有空容错运算符的对立面吗?

将类移动到新命名空间后更新RavenDB Raven-Clr-Type

如何在onNext之前等待订阅者完成?

源代码生成器项目使用`dotnet build`编译,而不是在Visual Studio中编译?

当我将`ConcurentDictionary`转换为`IDictionary`时,出现了奇怪的并发行为

用MongoDB c#驱动程序删除和返回嵌套数组中的文档

为什么当我try 为玩家角色设置动画时,没有从文件夹中拉出正确的图像?

Xamarin.Forms中具有类似AspectFill的图像zoom 的水平滚动视图

使用Try-Catch-Finally为API端点处理代码--有什么缺点?

如何在C#中用Serilog记录类路径、方法名和行编号