方式1:
private void button2_Click(object sender, EventArgs e) { m_th = new Thread(new ThreadStart(CheckDogJob)); m_th.IsBackground = true; m_th.Start(); } private async void CheckDogJob() { try { Console.Write("start----"); await Task.Delay(3000000, m_cts.Token); Console.Write("End----"); } catch (OperationCanceledException) { Console.Write("Cancel----"); } } private void button3_Click(object sender, EventArgs e) { m_cts.Cancel(); }
方式二:
private void button2_Click(object sender, EventArgs e) { m_th = new Thread(new ThreadStart(CheckDogJob)); m_th.IsBackground = true; m_th.Start(); } private void CheckDogJob() { Console.Write("start----"); Task.Delay(3000000, m_cts.Token).ContinueWith((t) => { Console.Write("Cancel----"); }, TaskContinuationOptions.OnlyOnCanceled).Wait(); Console.Write("End----"); } private void button3_Click(object sender, EventArgs e) { m_cts.Cancel(); }
方式三
private AutoResetEvent m_startDelayEvent = new AutoResetEvent(false); priviate void Test() { m_startDelayEvent.WaitOne(100000); } //取消 m_startDelayEvent.Set();