复制代码 代码如下:
public class Example
{
public static void Main()
{
CancellationTokenSource cts = new CancellationTokenSource();
var thread = new Thread(ThreadWork);
thread.Start(cts.Token);
while (true)
{
if(Console.ReadKey().KeyChar == 'c')
{
Console.WriteLine("请求取消线程的执行");
cts.Cancel();
break;
}
}
Console.ReadLine();
}
private static void ThreadWork(object state)
{
CancellationToken cancellationToken = (CancellationToken)state;
while (true)
{
// 检查是否取消
if(cancellationToken.IsCancellationRequested)
{
Console.WriteLine("线程已经取消了");
Console.WriteLine("线程的资源已经清理完成。");
break;
}
// 模拟工作
Thread.SpinWait(500000);
Console.WriteLine("我还在工作。");
}
}
}
复制代码 代码如下:
public class Example
{
private static int Value;
public static void Main()
{
var autoResetEvent = new AutoResetEvent(false);
var cts = new CancellationTokenSource();
var state = new { ValueAvailableEvent = autoResetEvent, CancellationToken = cts.Token };
var threadConsumer = new Thread(ConsumerThreadWork);
var threadProducter = new Thread(ProducterThreadWork);
threadConsumer.Start(state);
threadProducter.Start(state);
while (true)
{
if (Console.ReadKey().KeyChar == 'c')
{
Console.WriteLine("请求取消线程的执行");
cts.Cancel();
break;
}
}
Console.ReadLine();
}
public static void ProducterThreadWork(dynamic state)
{
var valueAvailableEvent = (AutoResetEvent)state.ValueAvailableEvent;
var cancellationToken = (CancellationToken)state.CancellationToken;
var rand = new Random();
while (!cancellationToken.IsCancellationRequested)
{
Value = rand.Next();
Console.WriteLine("/r/n产生一个值{0}", Value);
valueAvailableEvent.Set();
Thread.Sleep(500);
}
Console.WriteLine("生产者线程被取消。");
}
public static void ConsumerThreadWork(dynamic state)
{
var valueAvailableEvent = (AutoResetEvent)state.ValueAvailableEvent;
var cancellationToken = (CancellationToken)state.CancellationToken;
var events = new[] { valueAvailableEvent, cancellationToken.WaitHandle };
while (true)
{
var eventIndex = WaitHandle.WaitAny(events);
// 处理数据
if (eventIndex == 0)
{
Console.WriteLine("处理值{0}。", Value);
}
// 处理取消事件
else if (eventIndex == 1)
{
Console.WriteLine("消费者线程被取消。");
break;
}
}
}
}
新闻热点
疑难解答
图片精选