C# 可取消的延时实现
方式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();
作者:碎心炼心
出处:http://www.cnblogs.com/karl-F
本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。