Click here to Skip to main content
15,913,055 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
i have a search thread in my project . the thread is created in 'Form1()' function:
objSearchThread = new Thread(this.Thread_Func);


when user clicks the 'search' button, Start() function is called:
private void Button_Search_Click(object sender, EventArgs e)
{
    objSearchThread.Start();
}


second clicked of this button, crashed! because the thread is 'Started' state. if i change my button clicked code, and i add 'new' command. it works without error or crashing:
private void Button_Search_Click(object sender, EventArgs e)
{
    objSearchThread = new Thread(this.Thread_Func);
    objSearchThread.Start();
}


doesn't it need to delete thread object(objSearchThread )? does it need to call Abort() or other functions, when thread working ends? is second code that i write here correct?
Posted

Rob is right about the running threads but there is no problem about creating a new thread each time the user clicks the search button because I suppose this thread will search for something and then end quickly, right? So there is no risk of creating hundreds of non-terminating threads.

There are 2 options:
1. create a unique thread and use some signaling to tell when to start the search, when it is done, and when to quit the thread.
2. create one thread per click (like you already did).

Option 2 is much simpler of course and is suitable for your case.

Additionnaly, I would recommand you to have a look to BackgroundWorker class. This class provides simple use of a background thread, can report progress, and supports cancelation.

And if you want a ready-to-use UI for that, you may want to have look there: ProgressForm: A simple form linked to a BackgroundWorker[^]
 
Share this answer
 
Well as you say, you can't start a thread twice for the first example.

In the second, on every click of the button you create a new thread and set it running - this sounds bad, you wouldn't want a user to be able to create an unlimited number of threads.

A running thread won't get garbage collected, even if you no longer have references to it, so you would need to tell it to stop. You can use Abort() for this but its an ugly solution. A better way is to use some signaling to tell the thread to terminate when it can, thus allowing it to do any clear up operations it needs.
 
Share this answer
 
Comments
Zon-cpp 22-Sep-14 8:07am    
what are the clear operations for a thread?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900