C#灵活控制多线程的状态(开始暂停继续取消)

ManualResetEvent类

ManualResetEvent是一个同步基元,用于在多线程环境中协调线程的执行。它提供了两种状态:终止状态和非终止状态。

在终止状态下,ManualResetEvent允许线程继续执行。而在非终止状态下,ManualResetEvent会阻塞线程,直到它的状态变为终止状态。

ManualResetEvent类有以下几个常用的成员方法:

  • Set():将ManualResetEvent的状态设置为终止状态,允许线程继续执行。
  • Reset():将ManualResetEvent的状态设置为非终止状态,阻塞线程。
  • WaitOne():阻塞当前线程,直到ManualResetEvent的状态变为终止状态。
  • WaitOne(int millisecondsTimeout):阻塞当前线程,直到ManualResetEvent的状态变为终止状态,或者超过指定的超时时间。

 实现暂停继续

form界面

form类的成员变量

开始按钮的代码

 private void btnStart_Click(object sender, EventArgs e){a = new ManualResetEvent(true);c = new CancellationTokenSource();Task.Factory.StartNew(() =>{try{for (int i = 0; i < 100; i++){if (c.IsCancellationRequested){throw new InvalidOperationException();}a.WaitOne();Invoke(new Action(() =>{label1.Text = i.ToString();}));Thread.Sleep(500);}}catch (InvalidOperationException){Invoke(new Action(() => label1.Text = "线程已经取消"));}}, c.Token);}

暂停继续按钮的代码

  private void btnStop_Click(object sender, EventArgs e){a.Reset();}private void btnCountinue_Click(object sender, EventArgs e){a.Set();}

实现取消 

CancellationTokenSource类

CancellationTokenSource 是用于取消操作的一个类。它提供了一种机制,允许你在需要时通知一个或多个线程停止执行。

以下是 CancellationTokenSource 的一些常用成员:

  • Cancel():请求取消操作。调用此方法会导致关联的 CancellationToken 对象的 IsCancellationRequested 属性为 true
  • Token:获取与 CancellationTokenSource 关联的 CancellationToken 对象。通过检查 IsCancellationRequested 属性可以确定是否请求了取消操作。
  • CancelAfter(int millisecondsDelay):在指定的延迟时间后请求取消操作。调用此方法等待指定的延迟时间后,会自动调用 Cancel() 方法。

取消按钮的代码

 private void btnCancle_Click(object sender, EventArgs e){a.Set();// 先将 ManualResetEvent 对象设置为终止状态,以允许线程继续执行c.Cancel();}