定义代理:
delegate void AddLogHandler(string log);
定义调用函数:
private void AddLog(string log)
{
if (txtLog.IsDisposed) // 这里的txtLog为文本控件名称
{
return;
}
// 从ui线程去操作ui
if (txtLog.InvokeRequired)
{
txtLog.Invoke(new AddLogHandler(AddLog), log);
}
else
{
txtLog.AppendText($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] {log}\r\n");
}
}
定义全局变量:
/// <summary>
/// 定时器
/// </summary>
private readonly Timer _timer = new Timer(1000)
{
AutoReset = true,
};
调用主调用代码:
// 定时输出线程池任务数
_timer.Elapsed += (_, args) =>
{
AddLog($"线程池当前在执行的任务数: {_threadPool.TaskCount}, 任务队列数: {_threadPool.QueueSize}");
};
_timer.Start();
本文介绍了一种在UI线程中安全地进行日志输出的方法,通过定义代理和使用Invoke方法来确保文本控件更新不会导致界面卡顿。同时,文章展示了如何利用定时器定期检查线程池状态并记录相关信息。
625

被折叠的 条评论
为什么被折叠?



