gpt4 book ai didi

c# - 如何从另一个线程在 TreeView 中添加对象

转载 作者:行者123 更新时间:2023-11-30 20:20:34 25 4
gpt4 key购买 nike

我有一个多线程应用程序,我需要将另一个线程的对象添加到 TreeView 。但我不断收到异常

Action being performed on this control is being called from the wrong thread. Marshal to the correct thread using Control.Invoke or Control.BeginInvoke to perform this action.

这是我的代码

ThreadPool.QueueUserWorkItem(new WaitCallback(GetFiles), entryPoint);

private void GetFiles(object entryPoint)
{
var localData = entryPoint as EntryPoint;
this.GetFiles(localData.DirectoryInfo, localData.TreeNode);
localData.ManualEvent.Set();
}

private void GetFiles(DirectoryInfo directory, TreeNode tree)
{
for (int i = 0; i < allFiles.GetLength(0); i++)
{
tree.Nodes.Add(allFiles[i].Name);
}
}

最佳答案

如错误状态所示,您需要在 UI 线程上执行与 UI 相关的操作。为此,您可以使用控件本身的 BeginInvoke

private void GetFiles(DirectoryInfo directory, TreeNode tree) 
{
if (TreeViewControl.InvokeRequired)
{
TreeViewControl.BeginInvoke((MethodInvoker)delegate
{
for (int i = 0; i < allFiles.GetLength(0); i++)
{
tree.Nodes.Add(allFiles[i].Name);
}
});
}
}

您可以找到更多信息here .

关于c# - 如何从另一个线程在 TreeView 中添加对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36137127/

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