gpt4 book ai didi

c# - 如何从 BackgroundWorker 线程中更新标签?

转载 作者:太空宇宙 更新时间:2023-11-03 19:59:04 25 4
gpt4 key购买 nike

当我使用 WinForms 时,我会在我的 bg_DoWork 方法中这样做:

status.Invoke(new Action(() => { status.Content = e.ToString(); }));
status.Invoke(new Action(() => { status.Refresh(); }));

但是在我的 WPF 应用程序中,我收到一条错误消息,提示 Label 不存在 Invoke

如有任何帮助,我们将不胜感激。

最佳答案

使用 BackgroundWorker 中已经内置的功能。当您“报告进度”时,它会将您的数据发送到在 UI 线程上运行的 ProgressChanged 事件。无需调用 Invoke()

private void bgWorker_DoWork(object sender, DoWorkEventArgs e)
{
bgWorker.ReportProgress(0, "Some message to display.");
}

private void bgWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
status.Content = e.UserState.ToString();
}

确保设置 bgWorker.WorkerReportsProgress = true 以启用报告进度。

关于c# - 如何从 BackgroundWorker 线程中更新标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30398006/

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