Skip to content

Instantly share code, notes, and snippets.

@gfoidl
Created May 19, 2018 18:07
Show Gist options
  • Save gfoidl/667fd69f9b96fb5d27987fa6bfdbcb6e to your computer and use it in GitHub Desktop.
Save gfoidl/667fd69f9b96fb5d27987fa6bfdbcb6e to your computer and use it in GitHub Desktop.
Task -> CancellationToken (benchmarks)
using System.Threading;
using System.Threading.Tasks;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
using System.Runtime.CompilerServices;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
var bench = new Bench();
var ct1 = bench.ContinueWith();
var ct2 = bench.GetAwaiter();
#if !DEBUG
BenchmarkRunner.Run<Bench>();
#endif
}
}
//-------------------------------------------------------------------------
[MemoryDiagnoser]
public class Bench
{
private Task _task = Task.CompletedTask;
[Benchmark(Baseline = true)]
public CancellationToken ContinueWith() => _task.AsCancellationToken1();
[Benchmark]
public CancellationToken GetAwaiter() => _task.AsCancellationToken2();
}
//-------------------------------------------------------------------------
public static class TaskExtensions
{
public static CancellationToken AsCancellationToken1(this Task task)
{
var cts = new CancellationTokenSource();
task.ContinueWith((_, s) => (s as CancellationTokenSource).Cancel(), cts, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
return cts.Token;
}
//---------------------------------------------------------------------
public static CancellationToken AsCancellationToken2(this Task task)
{
var cts = new CancellationTokenSource();
task.GetAwaiter().UnsafeOnCompleted(cts.Cancel);
return cts.Token;
}
}
}
@gfoidl
Copy link
Author

gfoidl commented May 19, 2018

BenchmarkDotNet=v0.10.14, OS=Windows 10.0.17134
Intel Core i7-7700HQ CPU 2.80GHz (Kaby Lake), 1 CPU, 8 logical and 4 physical cores
Frequency=2742192 Hz, Resolution=364.6718 ns, Timer=TSC
.NET Core SDK=2.1.300-rc1-008673
  [Host]     : .NET Core 2.1.0-rc1 (CoreCLR 4.6.26426.02, CoreFX 4.6.26426.04), 64bit RyuJIT
  DefaultJob : .NET Core 2.1.0-rc1 (CoreCLR 4.6.26426.02, CoreFX 4.6.26426.04), 64bit RyuJIT

Method Mean Error StdDev Scaled ScaledSD Gen 0 Allocated
ContinueWith 254.1 ns 1.136 ns 1.007 ns 1.00 0.00 0.0558 176 B
GetAwaiter 526.7 ns 10.417 ns 14.259 ns 2.07 0.06 0.0525 168 B

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment