2011-12-06 30 views
-1

我有以下代碼:停止在C#中的操作或將其更改爲線程?

void ThreadMethod() 
{ 
    Console.WriteLine("Thread.."); 
} 

IAsyncResult actionResult; 

Action a = new Action(); 
Thread t = new Thread(new ThreadStart(ThreadMethod)); 

actionResult = a.BeginInvoke(ActionCompleted, null); 
t.Start(); 

void ActionCompleted(IAsyncResult ar) 
{ 
    if (ar.IsCompleted) 
    { 
     Console.WriteLine("Action finished"); 
     t.Abort(); 
    } 
} 

我怎樣才能手動停止動作? 例如

if (actionShouldBeStopped) 
{ 
    action.Stop(); // and ActionComplete should be run. 
} 

另一種方法是更改​​的操作主題,但隨後應該怎麼樣子?我如何實現像ActionCompleted for Thread這樣的東西?

感謝, 大師

+0

請參閱[此SO線程:鎖定並收聽CancellationToken](http://stackoverflow.com/q/7416786/485076)也許你會發現有用的東西 – sll

回答

2

我想您的實現切換從Threadthe BackgroundWorker class,它支持消除(即停止線),進度報告,並具有當線程完成(RunWorkerCompleted事件)

一個事件