I want to kill/destroy the thread in my application on Button Click event.
private void stop_btn_Click(object sender, EventArgs e)
{
Thread.Sleep();
}
Does this event hang up my application?
That’s the code where from my thread starts
DataTable myTable = new DataTable();`enter code here`
myTable = msgDataSet.Tables["text"];
DataRow[] myRow;
myRow = myTable.Select();
for (int x = 0; x < myRow.Count(); x++ )
{
SendKeys.SendWait(myRow[x]["msg"].ToString());
SendKeys.SendWait("{Enter}");
int sleep = int.Parse(textBox2.Text);
Thread.Sleep(sleep);
}
Thread Spam1 = new Thread(new ThreadStart(Send1));
Spam1.Start();
See this article for why you should never try to call
Thread.Abort:http://www.interact-sw.co.uk/iangblog/2004/11/12/cancellation
The problem is that you break your exception safety within that thread. This is because
Thread.Abortwill throw an exception within that thread at some arbitrary point, which might be right after a resource is loaded, but before the thread enters a try/catch that would support clean unloading of that resource.Instead you should build co-operative cancellation into the code you run in that thread. Then set some sort of “cancellation requested” state, and let the thread kill itself. E.g.:
In this case you’d expose
isCancelled, and have your parent thread set it totrue.This pattern is made clear if you use a
BackgroundWorkerto implement your background thread.