【问题标题】:C# Cancelling asynch thread immediatelyC#立即取消异步线程
【发布时间】:2011-11-23 17:33:33
【问题描述】:

我在按下启动按钮时启动一个线程,该按钮启动一个延迟计时器,然后显示一个消息框对话框。 现在,我试图停止这个线程,但我找不到办法,除了添加一个标志,它会阻止线程显示 messageBox 对话框但不会杀死线程。 如果您能提出一种杀死线程的方法,我将不胜感激。

谢谢 莫提

public partial class Form1 : Form
{
    public delegate void example();
    ThreadA threadA = null;

    public Form1()
    {
        InitializeComponent();
    }

    example ex;
    IAsyncResult result;
    private void button_Start_Click(object sender, EventArgs e)
    {
            ex = new example(start);//.BeginInvoke(null, null);
            result = ex.BeginInvoke(null, null);
    }

    private void button_Stop_Click(object sender, EventArgs e)
    {
        if (threadA != null)
            threadA = null;
    }

    private void start()
    {
        if (threadA == null)
        {
            threadA = new ThreadA();
            threadA.run();
        }
    }

}




class ThreadA
{
    //public event
    public Boolean flag = false;
    public void run()
    {
        Thread.Sleep(15000);
        MessageBox.Show("Ended");
    }
}

【问题讨论】:

标签: c# multithreading begininvoke


【解决方案1】:

我会使用带有CancellationTokenSourceTask 类。

 CancellationTokenSource cts = new CancellationTokenSource();
 Task t = new Task(() => new ThreadA().run(cts.Token), cts.Token); 

  // Start
  t.Start();
  ShowMessageBox(cts)

Edit2:对您的评论:

void ShowMessageBox(CancellationTokenSource cts)
{ 
    if(MessageBox.Show("StopThread",
    "Abort",MessageBoxButtons.YesNo,
     MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
    {
      cts.Cancel();
  }       
}

【讨论】:

  • 在我看来,这个解决方案会杀死 MessageBox 但不会杀死线程(ThreadA)。我对吗?因为我的意思是按下 STOP 按钮会杀死线程,即使它延迟 15 秒。
【解决方案2】:

使用ManualResetEvent

class ThreadA
{
    ManualResetEvent _stopEvent = new ManualResetEvent(false);
    Thread _thread;

    public Boolean flag = false;
    public void run()
    {
        while (true)
        {
            if (_stopEvent.Wait(15000))
                return; // true = event is signaled. false = timeout

            //do some work
        }

        MessageBox.Show("Ended");
    }

    public void Start()
    {
        _stopEvent.Reset();
        _thread = new Thread(run);
        _thread.Start();
    }

    public void Stop()
    {
        _stopEvent.Set();
        _thread.Join();
        _thread = null;
    }
}

但是,如果线程不会一直工作,我会使用Timer

【讨论】:

    猜你喜欢
    • 2020-09-08
    • 2017-07-28
    • 1970-01-01
    • 1970-01-01
    • 2021-11-22
    • 2023-03-28
    • 1970-01-01
    • 2019-05-28
    • 1970-01-01
    相关资源
    最近更新 更多