Skip to content

Instantly share code, notes, and snippets.

@shoter
Created December 14, 2020 21:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shoter/d943500eda37c7d99461ce3dace42141 to your computer and use it in GitHub Desktop.
Save shoter/d943500eda37c7d99461ce3dace42141 to your computer and use it in GitHub Desktop.
is WithContinue faster?
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace _13
{
public class AggregateExceptions
{
const int N = 10_000;
CancellationToken token = default(CancellationToken);
private Task ExceptionThrowingTask()
{
return Task.Factory.StartNew(async () =>
{
throw new Exception("test");
await Task.Delay(1000);
}, default(CancellationToken),
TaskCreationOptions.None,
TaskScheduler.Default);
}
[Benchmark]
public async Task WithoutContinue()
{
var tasks = new Task[N];
var exceptions = new Exception[N];
for(int i = 0;i < N; ++i)
{
tasks[i] = ExceptionThrowingTask();
}
for(int i = 0;i < N; ++i)
{
try
{
await tasks[i];
}
catch(Exception e)
{
exceptions[i] = e;
}
}
}
[Benchmark]
public async Task WithContinue()
{
var tasks = new Task[N];
var exceptions = new Exception[N];
for (int i = 0; i < N; ++i)
{
tasks[i] = ExceptionThrowingTask();
}
for (int i = 0; i < N; ++i)
{
await tasks[i].ContinueWith(_ => { }, token, TaskContinuationOptions.None, TaskScheduler.Current);
if (tasks[i].IsFaulted)
{
exceptions[i] = tasks[i].Exception;
}
}
}
}
class Program
{
public static async Task Test()
{
await Task.Delay(500);
throw new Exception();
}
static void Main(string[] args)
{
var summary = BenchmarkRunner.Run<AggregateExceptions>();
}
}
}
@shoter
Copy link
Author

shoter commented Dec 14, 2020

BenchmarkDotNet=v0.12.1, OS=Windows 10.0.18363.1256 (1909/November2018Update/19H2)
Intel Core i7-9750H CPU 2.60GHz, 1 CPU, 12 logical and 6 physical cores
.NET Core SDK=5.0.101
  [Host]     : .NET Core 3.1.10 (CoreCLR 4.700.20.51601, CoreFX 4.700.20.51901), X64 RyuJIT
  DefaultJob : .NET Core 3.1.10 (CoreCLR 4.700.20.51601, CoreFX 4.700.20.51901), X64 RyuJIT

Method Mean Error StdDev Median
WithoutContinue 412.4 ms 8.23 ms 22.79 ms 402.2 ms
WithContinue 427.0 ms 8.54 ms 25.17 ms 413.1 ms

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