I'm very new to threads, so my thoughts and questions might be a bit silly :)
I fill WinForm
control with data from another thread, so I have to call Invoke()
when I'm trying to access control.
If I understand correctly, treeView.BeginInvoke(/*some Action()*/)
makes this Action<>()
run in main thread. But I "fire and forget" this BeginInvoke()
, so I can't know when the work is actually done. And even when worker thread closes and execution returns to main thread, I can't be sure that all BeginInvoke()
methods have finished execution.
That's why even after returning to main thread I can't manage with Control
to which I fired BeginInvoke()
.
The actual problem is TreeView.ExpandAll()
doesn't work.
Take a look at the code snippet below.
private void btnGetTree_Click(object sender, EventArgs e) {
var treeViewWriter = new Thread(() => UpdateTreeView(new AddXmlNodeArgs(di, null), treeDirectoryContents));
treeViewWriter.Start();
treeViewWriter.Join();
treeDirectoryContents.ExpandAll();
}
// method runs on a worker thread
public static void UpdateTreeView(AddXmlNodeArgs args, TreeView treeView) {
// I will miss details... Here is the code that I run for every new TreeNode:
treeView.UpdateTree((TreeView tree) => {
tree.Nodes[0].Nodes.Add(newTreeNode); // treeView.Nodes[0]...
});
}
// Extension method for TreeView
public static void UpdateTree(this TreeView tree, Action<TreeView> code) {
if (tree.InvokeRequired)
tree.BeginInvoke(code, tree);
else
code.Invoke(tree);
}
I fire tree.BeginInvoke()
but I don't call EndInvoke()
anywhere. So I guess when in btnGetTree_Click
execution reaches to treeDirectoryContents.ExpandAll()
- not all Invoke()
methods have finished their work. Thats why .ExpandAll() doesn't work
.
Correct me if I'm wrong, and please give an advice how to solve this problem.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…