简体   繁体   English

在文本框中实时搜索

[英]real-time search in textbox

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... 每次更改文本时都会进行搜索(事件textbox.TextChanged)-这意味着有很多新的线程和已处置的线程...

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 这是C#4.0中的Win-form项目

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. 同样,Peter关于使用Task的建议类似于使用Thread Pool ,因为默认情况下Tasks在Thread Pool运行。

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. 最好在开始新搜索之前先“取消”当前搜索。

I have some suggestions: 我有一些建议:

  1. Use Task if you have a naturally asynchronous search system (eg Entity Framework async API), If not use ThreadPool . 如果您具有自然的异步搜索系统(例如Entity Framework async API),则使用Task ;如果不使用ThreadPool ,则使用Task

  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 textbox.TextChanged事件中启动一个计时器,并在每次文本更改时将其重置,如果计时器到达该计时器结束(1秒),然后尝试搜索,则这种方法避免了在快速键入abc时搜索aababc ,搜索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. 将一个时间戳记附加到每个搜索线程,并在准备好结果后将其保存在您的UI中,如果某个线程的结果已准备好并且当前结果时间戳大于准备就绪的时间戳记,则忽略该结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM