I am implementing a autocomplete control. Every time the user types a new character into a input, a query will fire. In order to test I have created a large database where the average query takes about 5 seconds to execute.
Because the query takes 5 seconds to execute I execute the query on a new thread:
// execute the following lamda expression when user enters characters to textbox
textBox1.TextChanged +=(x,eventArgs)=>{
// execute query on separate thread
new Thread(new ThreadStart(() =>
{
ObservableCollection = MyEntities.Entities.Products.Where(p => p.Name.Contains(inputText));
})).Start();
};
ObservableCollection and inputText are properties binded to my textbox and list.
The problem is that if the user types two characters my program will be running two threads at the same time. How can I abort the query?
Things that I am thinking about:
Create a bool variable IsQueryRuning and set it equal to true quen query starts and equal to false when thread ends. If a new query will be executed and IsQueryRuning = true then I can set ObservableCollection =null and cause an exeption. I will then resove it with a try catch block. I think that technique is not the best approach..
Edit:
Setting property Collection=null sometimes causes an exception and some other times it does not…
I would suggest a different approach, if that is possible to change for you.
Instead of querying on each keystroke of the user, I would only do a query after, for example, 3 characters. Keep the result in some collection in memory.
After that, only do the next queries on the in-memory collection. That spares you any following database accesses that are always much slower and ou should get a considerable performance gain.