c# - Dictionary 和 BackGroundWorker,收到 InvalidOperationException

标签 c#

我一定是误解了什么,因为我不知道为什么这不起作用。

我有一个名为 loadfile 的字典。

public Dictionary<string, string> loadfile;

此词典填充有从文件中读取的条目。

例如,如果我执行以下操作?

MessageBox.Show(loadfile["someentry"]);

消息框将显示字符串“someentry”中的值。

但是..如果我做同样的事情,但我不想在消息框中显示它,而是想在文本框中显示它,如下所示:

textBox1.Text = loadfile["someentry"];

它抛出一个异常(我在 try-catch 中运行它)。

我在这里错过了什么?

最佳答案

System.InvalidOperationException - Can it be because im running it inside a background worker?

是的,这可能就是问题所在。问题不在于从字典中获取值,而在于设置用户界面元素的 .Text 属性。

所有 UI 访问都必须在 UI 线程上完成。您需要将回调编码(marshal)回 UI 通过 Control.Invoke (Windows 窗体) 或 Dispatcher.Invoke (WPF) 进行线程。

例如,如果这是 Windows 窗体,您可以执行以下操作:

var entry = loadfile["someentry"];
textBox1.BeginInvoke(new Action(() => textBox1.Text = entry));

关于c# - Dictionary 和 BackGroundWorker,收到 InvalidOperationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21417484/

相关文章:

C# 转换泛型(协变和逆变?)

c# - float 错误计算

c# - 如何匹配自定义 PropertyGrid BrowsableAttributes 条目?

c# - 如何消除波形中的细微跳跃?

c# - 添加一种在 CSV 中将逗号保留到 DataTable 函数的方法

c# - Google Play 开发者 API - C# - 示例不起作用

c# - 如何将 IntPtr 转换为 native C++ 对象

c# - 以 root 身份运行时以用户身份启动外部进程

c# - MVC : The call is ambiguous between the following methods or properties

c# - 我应该将私有(private)方法提取到单元测试类吗?