2011-11-23 66 views
1

當按下啓動按鈕啓動一個延遲計時器,然後顯示一個messageBox對話框時,我啓動一個線程。 現在,我試圖阻止這個線程,但我無法找到一個方法,除了添加一個標誌,這將阻止線程顯示messageBox對話框,但不殺死線程。 如果你能提出一種殺死線程的方法,我將不勝感激。C#立即取消異步線程

感謝 莫蒂

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"); 
    } 
} 
+0

可能重複的[如何在C#中立即殺死線程?](http://stackoverflow.com/questions/1327102/how-to-kill-a-thread-instantly-in-c) – James

回答

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

對我而言,此解決方案殺死MessageBox而不是線程(ThreadA)。我對嗎?因爲我的意思是按下停止按鈕會在15秒的延遲時間內殺死線程。 – Moti

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