gpt4 book ai didi

C# 从后台线程更新 Windows 窗体中的 UI

转载 作者:行者123 更新时间:2023-11-30 19:49:04 24 4
gpt4 key购买 nike

http://www.codeproject.com/KB/threads/winformsthreading.aspx

我正在尝试使用上面的方法,虽然它在某种意义上起作用(它不会锁定我的应用程序),但不幸的是它没有更新 UI 上的标签。我在某处出错了吗?我在 MainForm 上有两个标签,expiredPoliciesLabel 和 missingPoliciesLabel。要更新它们,我必须通过执行一系列数据库查询来设置 expiredPoliciesNum 和 missingPoliciesNum,如您所见。我需要标签每分钟左右自动更新一次。 (我知道现在我将它设置为 1 秒,这只是为了查看代码是否正常工作)

这是我的代码。

public delegate void updatePolicyLabelsDelegate();

public partial class MainForm: Form
{
SQLiteQuery sqliteQuery = new SQLiteQuery(Properties.Settings.Default.DatabasePath);
int expiredPoliciesNum = 0;
int missingPoliciesNum = 0;
Thread minimizeThread;

public MainForm()
{
this.Resize += new EventHandler(MainForm_Resize);
this.IsMdiContainer = true;
InitializeComponent();
this.ShowInTaskbar = false;

keyValidation();

Thread bottomLabelsThread = new Thread(new ThreadStart(updateLabels));
bottomLabelsThread.IsBackground = true;
}

public void updateLabels()
{
while (true)
{
Invoke(new updatePolicyLabelsDelegate(updatePolicyLabels));
Thread.Sleep(1000);
}
}

private void updatePolicyLabels()
{
DataTable dt = sqliteQuery.selectFromDatabase("*", "WHERE GLOPolicy != '1'");
missingPoliciesNum = dt.Rows.Count;

dt = sqliteQuery.selectFromDatabase("*", "WHERE ALPolicy != '1'");
missingPoliciesNum = missingPoliciesNum + dt.Rows.Count;

dt = sqliteQuery.selectFromDatabase("*", "WHERE WCPolicy != '1'");
missingPoliciesNum = missingPoliciesNum + dt.Rows.Count;

dt = sqliteQuery.selectFromDatabase("*", "WHERE ULPolicy != '1'");
missingPoliciesNum = missingPoliciesNum + dt.Rows.Count;

String now = DateTime.Now.Year + "-" + DateTime.Now.Month + "-" + DateTime.Now.Day;

dt = sqliteQuery.selectFromDatabase("*", "WHERE GLOPolicy = '1' AND GLOExpiration < '" + now + "'");
expiredPoliciesNum = dt.Rows.Count;

dt = sqliteQuery.selectFromDatabase("*", "WHERE ALPolicy = '1' AND ALExpiration < '" + now + "'");
expiredPoliciesNum = expiredPoliciesNum + dt.Rows.Count;

dt = sqliteQuery.selectFromDatabase("*", "WHERE WCPolicy = '1' AND WCExpiration < '" + now + "'");
expiredPoliciesNum = expiredPoliciesNum + dt.Rows.Count;

dt = sqliteQuery.selectFromDatabase("*", "WHERE ULPolicy = '1' AND ULExpiration < '" + now + "'");
expiredPoliciesNum = expiredPoliciesNum + dt.Rows.Count;


expiredPoliciesLabel.Text = expiredPoliciesNum + " Expired Policies ";
missingPoliciesLabel.Text = missingPoliciesNum + " Missing Policies ";
}

感谢您的帮助,我是线程的新手,可以使用一些专业知识,信不信由你,我到处搜索试图找出我出错的地方无济于事。

最佳答案

您创建了线程对象,但并未启动它,正如您的代码所显示的那样:

bottomLabelsThread.Start();

它不会自动启动。

关于C# 从后台线程更新 Windows 窗体中的 UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4543264/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com