问题
How can I end my thread with a button click? I start my thread with a button click.
new Thread(SampleFunction).Start();
and my thread:
void SampleFunction()
{
int i = 0;
while (true)
{
string Seconds = DateTime.Now.ToString("ss");
if (Seconds == "00")
{
int i2 = i++;
string myString = i2.ToString();
AppendTextBox(myString);
Thread.Sleep(2000);
}
}
}
public void AppendTextBox(string value)
{
if (InvokeRequired)
{
this.Invoke(new Action<string>(AppendTextBox), new object[] { value });
return;
}
textBox4.Text += value;
}
How do i cancel it? the following doesn't work:
private void button8_Click(object sender, EventArgs e)
{
SampleFunction.Abort();
}
回答1:
SampleFunction
is a method, not a Thread
object, so you can't call Abort() like that.
You need to keep a reference to the Thread
:
var thread = new Thread(SampleFunction);
thread.Start();
Then you can call Abort()
when you want to kill it:
thread.Abort();
But keep in mind that it does kill it. The effect of Abort()
is that it throws a ThreadAbortException
in the thread. So it can stop at any moment and leave things in an unexpected state, so it may not be the best approach depending on what you're doing in the thread.
Here are a couple articles that discuss this and possibly better ways to stop a thread:
- Destroying threads
- Canceling threads cooperatively
来源:https://stackoverflow.com/questions/53462913/c-sharp-stop-thread-with-a-button-click