Are there drawbacks if we create a short-life thread (200 ms to 1 second) to perform a search task on every keypress in a Textbox field?
std::wstring query;
void DoTheSearch ()
{
// 200ms to 1sec long processing that would block the GUI if no dedicated thread
// search a database using query variable
}
// main window message loop
case WM_COMMAND:
// ...
if (wmEvent == EN_CHANGE)
{
query = GetTheQueryStringFromTextBox(...);
DWORD threadID;
HANDLE hThread = CreateThread(NULL, 0, DoTheSearch, NULL, 0, &threadID);
// there will be a lot (for each keypress) of short-life threads often
}
Or should I make only one thread for the search (with a while (True)
idle most of the time, and with Sleep(10);
inside?).
Note: I've also implemented a "debouncing" feature to avoid as many searches than every keypress, but this is out of the topic here.
答案 0 :(得分:2)
与流行的观点相反,创建一个线程并不昂贵。虽然我没有Windows机器进行测试,但我认为现代Windows系统上的线程创建时间在单个微秒单位内(就像在Linux上一样)。
因此,如果您的设计变得更简单,使用短暂的线程场景,并且线程没有上下文来保持,并且在任何给定时间您只有一个工作线程,并且它们不是经常启动(例如,每个10秒或更长时间)我认为没有特别的理由让设计弯曲以允许线程消息排队。