我希望在下達指令時完全中止線程...但我5秒就按button2來跑abort...為何thread的迴圈還一直記數沒停呢?
delegate void test2();
private void button1_Click(object sender, EventArgs e)
{
th = new Thread(disp);
th.Start();
}
private void button2_Click(object sender, EventArgs e)
{
try
{
if (th.ThreadState != ThreadState.Aborted)
th.Abort();
//th.Interrupt();
}
catch (ThreadAbortException ee)
{ }
}
void disp()
{
try
{
for (; ; )
{
if (this.InvokeRequired)
{
test2 use = new test2(disp);
this.Invoke(use);
}
else
{
Thread.Sleep(1000);
Application.DoEvents();
string[] ss = label3.Text.Split('_');
label3.Text = th.ThreadState.ToString() + "_" + (int.Parse(ss[1]) + 1);
}
}
}
catch { }
}
private CancellationTokenSource cts;
private void button1_Click(object sender, EventArgs e)
{
cts = new CancellationTokenSource();
Task.Factory.StartNew(() => disp(cts.Token), cts.Token);
}
private void button2_Click(object sender, EventArgs e)
{
cts?.Cancel();
}
void disp(CancellationToken token)
{
try
{
while (!token.IsCancellationRequested)
{
this.BeginInvoke(new Action(() =>
{
string[] ss = label3.Text.Split('_');
label3.Text = th.ThreadState.ToString() + "_" + (int.Parse(ss[1]) + 1);
}));
Thread.Sleep(1000);
}
}
catch (OperationCanceledException)
{
}
}