Created
February 19, 2014 01:23
-
-
Save mattjohnsonpint/9084379 to your computer and use it in GitHub Desktop.
Test showing parallel async tasks
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.Collections.Generic; | |
using System.Diagnostics; | |
using System.Linq; | |
using System.Threading.Tasks; | |
using Microsoft.VisualStudio.TestTools.UnitTesting; | |
namespace Tests | |
{ | |
[TestClass] | |
public class AsyncTest | |
{ | |
[TestMethod] | |
public async Task Test() | |
{ | |
var sw = new Stopwatch(); | |
sw.Start(); | |
var results = await this.GetFoosAndDoSomethingAsync(); | |
sw.Stop(); | |
foreach (var foo in results) Debug.WriteLine(foo.X); | |
Debug.WriteLine(sw.ElapsedMilliseconds); | |
} | |
public async Task<IList<Foo>> GetFoosAndDoSomethingAsync() | |
{ | |
var foos = Enumerable.Range(0, 10).Select(x => new Foo(x)); | |
var tasks = foos.Select(async foo => await DoSomethingAsync(foo)); //.ToList(); | |
return await Task.WhenAll(tasks); | |
} | |
private async Task<Foo> DoSomethingAsync(Foo foo) | |
{ | |
await Task.Delay(1000); | |
return foo; | |
} | |
} | |
public class Foo | |
{ | |
public Foo(int x) | |
{ | |
X = x; | |
} | |
public int X { get; set; } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment