Skip to content

Instantly share code, notes, and snippets.

@mattjohnsonpint
Created February 19, 2014 01:23
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 mattjohnsonpint/9084379 to your computer and use it in GitHub Desktop.
Save mattjohnsonpint/9084379 to your computer and use it in GitHub Desktop.
Test showing parallel async tasks
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