c# - Debug.WriteLine 不适用于不同的线程

标签 c# multithreading

<分区>

var timer = new Timer
{
    Enabled = true, 
    Interval = 500
};
Debug.WriteLine("new timer created");
timer.Elapsed += (s, e) =>
{
    Debug.WriteLine("hello from timer");
    // this doesn't get shown
    // in the output window
}

我需要做什么才能在上面的输出窗口中看到我的最后一个 Debug.WriteLine()

最佳答案

您实际上并没有使用单独的线程,System.Timers 计时器在 UI 消息泵上运行(如果可用)。如果您阻塞了 UI 线程,计时器将永远不会运行。

检查 UI 线程是否未被阻塞,use System.Threading.Timer that does not use the UI thread , 或设置 SynchronizingObjectnull,因此它将使用线程池线程而不是 UI 线程。

编辑:或喜欢 Hans said in his comment ,您正在控制台中运行并且 Main() 在计时器有机会触发之前退出。

关于c# - Debug.WriteLine 不适用于不同的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20598934/

相关文章:

c# - BOTS框架,空属性无法加密

ios - 乱序调用的 GCD 函数

java - 异步任务的线程池?

c - 从一个线程切换到另一个出现段错误

java - 当前 worker 是否参与工作窃取?

c# - 必须声明标量变量 "@dom"

c# - MailMerge:从 Excel 到 Word C#

java - Swing 进度条通过 Worker 更新到 EventDispatch 线程

c# - 在UWP for Store Apps中引用sqlite3.dll

c# - 如何在 C# 中编码这个嵌套的、可变长度的 C 结构