c# - C# Win-Forms 用户控件后台任务执行延迟
问题描述
我有 C# Windows 窗体应用程序,它由窗体和用户控件组成。
我尝试在添加到表单的用户控件内的后台线程中运行代码,这是我在用户控件中使用的代码:
private void button3_Click(object sender, EventArgs e)
{
ShowNotification("Invoke", $"Start Invoke { DateTime.Now}");
Task.Run(() =>
{
ShowNotification("Run", $"Start Run { DateTime.Now}");
});
}
private void ShowNotification(string title, string message, ToolTipIcon icon = ToolTipIcon.Info)
{
notifyIcon1.ShowBalloonTip(20, title, message, icon);
}
在发布模式下运行此项目时,执行没有问题。但是,在调试模式下运行此项目时,Task.Run 中的代码在按下按钮 1.5 分钟后执行,这意味着在第一个通知的 1.5 分钟后显示第二个通知。
任何人都知道为什么会这样?
编辑:
在对这个问题进行了更多搜索后,我发现这个问题有助于解决这个问题:
替换:
Task.Run(() =>
{
ShowNotification("Run", $"Start Run { DateTime.Now}");
});
和:
var notificationThread =
new Thread(() =>
{
ShowNotification("Run", $"Start Run {DateTime.Now}");
})
{ IsBackground = true};
notificationThread.Start();
已经解决了问题。
解决方案
尝试调用线程。
private void ShowNotification(string title, string message, ToolTipIcon icon = ToolTipIcon.Info)
{
MethodInvoker Invoker = new MethodInvoker(delegate
{
notifyIcon1.ShowBalloonTip(20, title, message, icon);
});
if (InvokeRequired)
{
this.Invoke(Invoker);
}
else
{
notifyIcon1.ShowBalloonTip(20, title, message, icon);
}
}
推荐阅读
- sql-server - 变量评估失败的 SQL Server 作业表达式
- javascript - SDK API 命名空间设计
- python - Python 中的 Turtle(Ball) 没有保持一致的速度?(乒乓)
- difference - 如何在多个数字中查找两个数字之间的特定差异
- r - 定义双向条形图中不同类型的颜色
- javascript - 如何在 Laravel 5.8 中使 chart.js 动画/增长/活着?
- python - 为什么不能复制列表并丢失列表的第一个索引?
- openlayers - 使用包含 LineStrings 的矢量源在 OpenLayers 中创建热图
- scala - Spark Structured Streaming Databricks 事件中心架构定义问题
- iis - 未创建 stdoutLog