gpt4 book ai didi

c# - 如何使用 BackgroundWorker 确保 UI 响应

转载 作者:太空狗 更新时间:2023-10-29 22:35:10 25 4
gpt4 key购买 nike

C# 中的 BackgroundWorker 线程安全吗?

我问这个的原因是因为我得到了一个

Controls created on one thread cannot be parented to a control on a different thread

异常(exception)。这是我的 DoWork 事件代码:

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{



var openFile = document.Open(MyFileName);
e.Result = openFile;
}

其中 document 是在创建父表单时初始化的 UI 控件。在 Open 方法期间,将填充 document 中的各种属性。

我尝试更改要调用的代码,但同样的问题仍然存在。即,

document.GetType().GetMethod("Open)".Invoke(document, new object[]{MyFileName})

将产生与上述相同的错误。

知道如何操作 document 控件吗?也就是说,如何让上面的代码生效呢?

编辑:有人建议我使用 Control.Invoke,但它仍然不起作用(两个线程都挂起)。这是我试过的代码:

private delegate bool OpenFile(string filePath);
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{



OpenFile oF = new OpenFile(document.Open);
var openFile = Invoke(oF, MyFileName); // it doesn't really matter whether I use BeginInvoke or Invoke, or other Control.Invoke, the end result is the same. Both the main thread hosting the document and the thread that launches the UI hanged.

e.Result = openFile;
}

最佳答案

问题不在于线程,而在于它试图调用 UI 控件上的方法。在 WPF 和 WinForms 中,控件只能在 UI 线程(通常有一个)上调用。你没有说你正在使用哪个,但你需要调用 Control.Invoke WinForms 或 Dispatcher.Invoke 的方法对于 WPF。

您显示的 Invoke() 反射方法将实际调用当前线程上的方法。

关于c# - 如何使用 BackgroundWorker 确保 UI 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2085067/

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