1

I have a textbox in which the user types a search string and then the program makes a search for that string on a background-working-thread.

Right now i'm re-using the same old thread (and wait to make a new search only when the thread is finished/cancelled).

I would be a lot easier if I could just create a new thread each time i want to make a search - because then I would not need to wait for the other thread to be completed before making the search.

The search occurs every time time the text is changed (event textbox.TextChanged) - so that means a lot of new and disposed threads...

Is this a viable strategy or should I continue re-using the same thread (makes room for a lot of potential bugs)?

This is a win-form project in C# 4.0

Hamid Pourjam
  • 20,441
  • 9
  • 58
  • 74
7382
  • 11
  • 3
  • 3
    Use the `Task` class. It uses the thread pool, which will avoid much of the overhead of creating a new thread. – Peter Duniho Dec 01 '14 at 07:18
  • `The search occurs every time the text is changed`, this is a real performance hit, you can add a timer, say, 1000 ms to tick, reset the timer at each key stroke, only after user stop typing (elapse 1000 ms until the timer ticks) that you do the searching. – kennyzx Dec 01 '14 at 07:32
  • Must you really use a background thread? How time consuming is the search operation? Hitting a background thread for every search is will cause a performance hit. – Yuval Itzchakov Dec 01 '14 at 07:37

2 Answers2

0

What you are looking for is called Thread Pool.

It is basically same thing as you are doing in a sense that it reuses a thread. Except that there are many threads and the reuse is hidden from the invoker. More explanation here.

Also, Peter's suggestion of using Task is similar to using Thread Pool, because Tasks run on Thread Pool by default.

And don't forget that you still have to solve a problem of having multiple searches running at the same time and that they might not finish in order that they were started nor can they have valid data for current search. It would be best if you could "cancel" the current search before starting a new one.

Community
  • 1
  • 1
Euphoric
  • 12,645
  • 1
  • 30
  • 44
0

I have some suggestions:

  1. Use Task if you have a naturally asynchronous search system (e.g Entity Framework async API), If not use ThreadPool.

  2. Start a timer in your textbox.TextChanged event and reset it every time the text changed, if the timer reachs it ends (1 sec) then try searching, this approaches avoid searching for a, ab and abc when you type abc fast and meant to search for abc

  3. attach a timestap to every search thread and when the result is ready save it somewhere in you UI, if result of a thread is ready and current result timestamp is bigger than the one being ready then ignore the result.

Hamid Pourjam
  • 20,441
  • 9
  • 58
  • 74