I want to make treeView of a hierarchy of files, which name match pattern and file has searched words. I need run it in task and have an ability of stopping and continuing this task or cancel it when search started with different parameters, I accomplished stoping/continuing with ManualResetEvent object. But I don't know how to cancel this task when async function is called again (Cancellation token doesn't work from async function). Have you any ideas or better way of doing it?
Code where I demonstrate how I use CancellationTokenSource to cancel last async function call.
private void buildFileSystemTreeView(TreeNode CurrentTreeNode, DirectoryInfo directoryInfo) { foreach (var f in directoryInfo.GetFiles(this.search_pattern)) { terminate.WaitOne(); if (this.tokenSource.IsCancellationRequested) { return; } CurrentTreeNode.Nodes.Add(f.Name); this.CurrentProcessingFileStatusLabel.Text = f.Name; this.ProcessedFilesCountStatusLabel.Text = $"{++processed_files_count,3} files processed"; } foreach (var d in directoryInfo.GetDirectories()) { CurrentTreeNode.Nodes.Add(d.Name); int i = CurrentTreeNode.Nodes.Count - 1; this.buildFileSystemTreeView(CurrentTreeNode.Nodes[i], new DirectoryInfo(d.FullName)); } } async void start_search() { this.tokenSource?.Cancel(); this.tokenSource = new CancellationTokenSource(); this.token = tokenSource.Token; DirectoryInfo directoryInfo = new DirectoryInfo(path); this.start_search_treeNode = new TreeNode(directoryInfo.Name); await Task.Run(() => { Thread.CurrentThread.IsBackground = true; this.buildFileSystemTreeView(this.start_search_treeNode, directoryInfo); }, token); }
terminate? are you sure that code doesn't block onterminate.WaitOne();?