(Ignore this crap if you only want to see some code)
So, I was coding this project where I have created a live search for a tree view and now I want to have a delay for the search to be done, so it wont update for each letter I write in the searchbox.
The first thing I did was to create a timer that would start when i wrote a letter. This did not work out so well because it required this thing safety for cross-thread operations or something. My first thought was “fuck it, lets try something else”. I have always been afraid of threading, so I tried to find another way to fix it.
But now, some hours later, when i have looked into threading some more I found a very simple way to solve my problem, but without the use of timers. Now with good old threading.
Ok now on to the code…
My problem is to update a controller from a thread it ain’t created from. In this case a treeview. And also i want a delay so.
public MyClass
{
bool searchStarted = false; //so it wont create a new search for each time the function is called, i.e. we got a textChanged listener on a textbox.
// I dont know what this crap is for, but we need it. If we do not want to pass any arguments, dont have any here.
private deligate void AddNodeToTreeViewDeligate(TreeNode nodeToAdd);
private void AddNodeToTreeView(TreeNode nodeToAdd)
{
Thread.Sleep(1000);
this.treeView.Nodes.Clear();
this.treeView.Nodes.Add(nodeToAdd);
searchStarted = false;
}
private void Search()
{
// ok i’v done a search and now my data is in the variable foundNodes
if(!searchStarted)
{
AddNodeToTreeViewDeligate d = new AddNodeToTreeViewDeligate(AddNodeToTreeView);
this.Invoke(d, new object[] {foundNodes}); //if we got no arguments, it will look like this: this.Invoke(d);
searchStarted = true;
}
}
}