Created
May 19, 2018 18:07
-
-
Save gfoidl/667fd69f9b96fb5d27987fa6bfdbcb6e to your computer and use it in GitHub Desktop.
Task -> CancellationToken (benchmarks)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} |
Author
gfoidl
commented
May 19, 2018
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