C#立即取消异步线程

时间:2011-11-23 08:43:12

标签: c# multithreading begininvoke

按下启动按钮启动延迟计时器,然后显示messageBox对话框,我启动一个线程。 现在,我试图阻止这个线程,但是我找不到方法,除了添加一个标志,这将阻止线程显示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");
    }
}

2 个答案:

答案 0 :(得分:1)

我将Task类与CancellationTokenSource一起使用。

 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();
  }       
}

答案 1 :(得分:0)

使用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