Just installed the VS2010RC version, experience. New cooperative cancellation mode for the NET4.0 thread pool.
Used. NET thread pool people know that once the code to execute to the thread pool to execute, we basically lost the code in the operation of the control ability. For example, if we want to cancel the execution of this code at some point, we have to think of another way. With. NET4.0 arrived, the problem was solved. NET4.0 introduces a new design pattern---Cooperative cancellation mode (cooperative cancellation).
. The System.Threading namespace of NET4.0 has two new members, one is the CancellationTokenSource class, the other is the cancellationtoken structure. The main members of the CancellationTokenSource class are as follows:
public sealed class CancellationTokenSource : IDisposable {
public CancellationTokenSource();
public void Dispose();
public Boolean IsCancellationRequested { get; }
public CancellationToken Token { get; }//CancellationToken结构
public void Cancel();
public void Cancel(Boolean throwOnFirstException);
}
The CancellationToken structure code is roughly as follows:
public struct CancellationToken
{
public Boolean IsCancellationRequested { get; }
public void ThrowIfCancellationRequested();
// 当CancellationTokenSource取消时使用的信号量
public WaitHandle WaitHandle { get; }
public static CancellationToken None { get; }
public Boolean CanBeCanceled { get; }
public CancellationTokenRegistration Register (Action<Object> callback, Object state, Boolean useSynchronizationContext);
}
Use the following code:
using System;
using System.Threading;
namespace Cooperativecancellation
{
Class program
{
static void Main (string[] args)
{
CancellationTokenSource cts = new Can Cellationtokensource ();
ThreadPool.QueueUserWorkItem (o => executeinthreadpool (CTS). Token));
Console.WriteLine ("Press <Enter> to cancel the operation");
Console.ReadLine ();
CTS. Cancel ();
Console.ReadLine ();
}
static void Executeinthreadpool (CancellationToken token)
{
Con Sole. WriteLine ("Enter in ThreadPool.");
while (!token). iscancellationrequested)
{
Console.Write (".");
Thread.Sleep (1000);
}
Console.WriteLine ("Operation is be cancel.");
}
}
}
The code is simple, I don't have to say much here. In short, with the cooperative cancellation model, we were right. NET thread pool, the execution of code has more control, it is a good function.