0
我有運行和分配一個新的樹視圖對象到treeFolders樹視圖形式對象這段代碼:異步使用異步和等待更新Winforms中一個TreeView
private async void butLoad_Click(object sender, EventArgs e)
{
Task<TreeView> task = Task.Run(() => DirectoryTree.ListDirectory("C:\\"));
this.treeFolders = await task;
}
我很高興作爲代碼不阻擋用戶界面,並遞歸目錄並建立一個TreeView對象。問題是,即使在運行此代碼之後,窗體上的TreeFolders TreeView對象仍然爲空。如果我在break模式下檢查treeFolders對象,我可以看到它確實有文件和目錄的節點,所以我不明白爲什麼它不顯示它們。這是否與樹視圖創建對UI線程的不同威脅有關?下面是這似乎是做工精細的ListDirectory和負載所需的所有目錄和文件
public class DirectoryTree
{
public static async Task<TreeView> ListDirectory(string path)
{
TreeView treeView = new TreeView();
var rootDirectoryInfo = new DirectoryInfo(path);
treeView.Nodes.Add(await CreateDirectoryNode(rootDirectoryInfo));
return treeView;
}
private static async Task<TreeNode> CreateDirectoryNode(DirectoryInfo directoryInfo)
{
try
{
var directoryNode = new TreeNode(directoryInfo.Name);
foreach (var directory in directoryInfo.GetDirectories())
directoryNode.Nodes.Add(await CreateDirectoryNode(directory));
foreach (var file in directoryInfo.GetFiles())
directoryNode.Nodes.Add(new TreeNode(file.Name));
return directoryNode;
}
catch (Exception ex)
{
var directoryNode = new TreeNode(directoryInfo.Name);
return directoryNode;
}
}
}
您不應在線程池線程上創建UI對象。相反,在內存中創建一個樹結構並從ListDirectory方法返回它,然後讓你的UI線程創建實際的UI對象('TreeNode'等)。 –
因爲你這樣做是C目錄你確定你沒有得到未經授權的例外嗎?輸出窗口在運行應用程序時說什麼 – WBuck
try catch塊處理未授權的異常 – ravetroll