Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@podhmo
Last active January 1, 2016 03:29
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 podhmo/8085926 to your computer and use it in GitHub Desktop.
Save podhmo/8085926 to your computer and use it in GitHub Desktop.
using System;
using System.Threading.Tasks;
namespace asyncAwaitSample
{
class MainClass
{
public static void Main (string[] args)
{
var m = new MainClass ();
var t = m.RunSequential ();
var t2 = m.RunPararell ();
var t3 = m.RunSequentialNoAwait ();
Task.WaitAll (t, t2, t3);
}
public async Task RunSequential ()
{
Console.WriteLine ("* Run Sequential *");
var t = await new Scene ("*").Run ();
var t2 = await new Scene ("*").Run ();
Console.WriteLine ("* sum: {0} *", t + t2);
}
public Task RunSequentialNoAwait ()
{
Console.WriteLine ("$ Run Sequential NoAwait $");
var tt = new Scene ("$").Run ().ContinueWith ((t) => {
new Scene ("$").Run ().ContinueWith ((t2) => {
Console.WriteLine ("$ sum: {0} $", t.Result + t2.Result);
}).Wait ();
});
return tt;
}
public Task RunPararell ()
{
Console.WriteLine ("- Run Pararell -");
var t = new Scene ("-").Run ();
var t2 = new Scene ("-").Run ();
return Task.WhenAll (t, t2).ContinueWith (((Task arg) =>
Console.WriteLine ("- sum: {0} -", t.Result + t2.Result)));
}
}
class Scene
{
private String tag;
public Scene (String name)
{
this.tag = name;
}
public void p (String prefix, int v)
{
Console.WriteLine ("{3} id={2} {0}: {1} {3}", prefix, v, this.GetHashCode (), tag);
}
public async Task<int> Run ()
{
p ("start", 0);
int a = await Task.FromResult (10);
p ("a", a);
await Task.Delay (200);
int b = await Task.FromResult (20);
p ("b", b);
return a + b;
}
}
}
@podhmo
Copy link
Author

podhmo commented Dec 22, 2013

* Run Sequential *
* id=421107885 start: 0 *
* id=421107885 a: 10 *
- Run Pararell -
- id=301241367 start: 0 -
- id=301241367 a: 10 -
- id=880988194 start: 0 -
- id=880988194 a: 10 -
$ Run Sequential NoAwait $
$ id=924151092 start: 0 $
$ id=924151092 a: 10 $
* id=421107885 b: 20 *
* id=551977066 start: 0 *
* id=551977066 a: 10 *
* id=551977066 b: 20 *
* sum: 60 *
- id=301241367 b: 20 -
- id=880988194 b: 20 -
- sum: 60 -
$ id=924151092 b: 20 $
$ id=277322821 start: 0 $
$ id=277322821 a: 10 $
$ id=277322821 b: 20 $
$ sum: 60 $

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