首页 > 解决方案 > 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();

已经解决了问题。

标签: c#multithreadingwinformstask

解决方案


尝试调用线程。

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

推荐阅读