iT邦幫忙

1

C# abort or Interrupt為何無法關閉停止線程呢?

  • 分享至 

  • xImage

我希望在下達指令時完全中止線程...但我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 { }
        }

https://ithelp.ithome.com.tw/upload/images/20230306/20141745e31BrLPtlX.png

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

1
JamesDoge
iT邦高手 1 級 ‧ 2023-03-07 06:38:21
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)
    {
    }
}

我要發表回答

立即登入回答