Created
December 14, 2020 21:26
-
-
Save shoter/d943500eda37c7d99461ce3dace42141 to your computer and use it in GitHub Desktop.
is WithContinue faster?
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 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>(); | |
} | |
} | |
} |
Author
shoter
commented
Dec 14, 2020
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