Skip to content

Instantly share code, notes, and snippets.

@Nilzor
Created June 24, 2016 14:15
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 Nilzor/54d1a4452a657bb3f4e68fd64c1b5aee to your computer and use it in GitHub Desktop.
Save Nilzor/54d1a4452a657bb3f4e68fd64c1b5aee to your computer and use it in GitHub Desktop.
Asynchronouse patterns in C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AsyncPatterns
{
class Program
{
static void Main(string[] args)
{
DoSerial().Wait();
}
private static void DoParallelAll()
{
var start = Environment.TickCount;
var tasks = new Task<int>[3];
tasks[0] = GetSlowIntTask(1);
tasks[1] = GetSlowIntTask(2);
tasks[2] = GetSlowIntTask(3);
Task.WaitAll(tasks);
for (int i = 0; i < 3; i++)
{
Console.Out.WriteLine(" Time: " + (Environment.TickCount - start));
Console.Out.WriteLine("Res " + i + ": " + tasks[i].Result);
}
}
private static void DoParallelFirst()
{
var start = Environment.TickCount;
var tasks = new Task<int>[3];
tasks[0] = GetSlowIntTask(1);
tasks[1] = GetSlowIntTask(2);
tasks[2] = GetSlowIntTask(3);
int firstResult = Task.WaitAny(tasks);
Console.Out.WriteLine(" Time: " + (Environment.TickCount - start));
Console.Out.WriteLine("Res " + firstResult);
}
private static async Task DoSerial()
{
var start = Environment.TickCount;
var tasks = new Task<int>[3];
var str = await GetSlowStringTask("Hello world");
var len = await GetSlowIntTask(str.Length);
var res = await GetSlowStringTask("Len: " + len);
Console.Out.WriteLine(" Time: " + (Environment.TickCount - start));
Console.Out.WriteLine(res);
}
public static async Task<string> GetSlowStringTask(String toReturn)
{
await Task.Delay(250);
return toReturn;
}
public static async Task<int> GetSlowIntTask(int toReturn)
{
await Task.Delay(250);
return toReturn;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment