取消進行中的Thread (使用Thread類別)
1.
由主程式結束Thread
Thread myThread = new Thread(() =>
{
//Do something
}}
);
myThread.Name = "Lesson77_Thread";
myThread.IsBackground = false;
myThread.Start();
{
//Do something
}}
);
myThread.Name = "Lesson77_Thread";
myThread.IsBackground = false;
myThread.Start();
//1. 由主程式結束Thread
myThread.Abort();
2.
使用協作式取消
u 定義一個 CancellationTokenSource 物件
u 在Thread中,判斷是否協作式取消物件CancellationTokenSource已取消。
u 可定義 CancellationTokenSource 物件取消後的CallBack 事件: Token.Register()
u 範例程式:
/// <summary>
/// 向 System.Threading.CancellationToken 發出訊號,表示應該將它取消
/// </summary>
static CancellationTokenSource cts = new CancellationTokenSource();
/// <summary>
/// 向 System.Threading.CancellationToken 發出訊號,表示應該將它取消
/// </summary>
static CancellationTokenSource cts = new CancellationTokenSource();
主程式 …
///CancellationTokenSource 取消時會呼叫的委派
cts.Token.Register(() =>
{
Console.WriteLine("Thread is canceled!");
});
///定義Thread
Thread myThread = new Thread(() =>
{
for (int i = 0; i < 10000; i++)
{
//在迴圈內判斷 協作式取消(Cancellation Token) 是否已取消? 若是,主動離開Thread。
if (cts.Token.IsCancellationRequested)
{
return;
}
Console.WriteLine("{0}", i.ToString());
}
});
myThread.IsBackground = false;
myThread.Start();
//2. 將 協作式取消(Cancellation Token) 打開 ,誘發Thread自行結束
cts.Cancel();
結果畫面
沒有留言:
張貼留言