Skip to content

Instantly share code, notes, and snippets.

@f-ewald
Last active July 27, 2016 23:36
Show Gist options
  • Save f-ewald/4d439a6f2623d88f9095df85eb9cd694 to your computer and use it in GitHub Desktop.
Save f-ewald/4d439a6f2623d88f9095df85eb9cd694 to your computer and use it in GitHub Desktop.
async/await c#
using System;
using System.ComponentModel;
using System.Text;
using System.Threading.Tasks;
namespace MultiThreadTest
{
class Program
{
static void Main(string[] args)
{
// Run the async method 10 times.
for (int i = 0; i < 10; i++)
{
RunSomethingAsync(i);
}
// Only as a run loop so that the output is visible.
while (true)
{
System.Threading.Thread.Sleep(500);
Console.WriteLine("Sleeping...");
}
}
static async void RunSomethingAsync(int i)
{
int z = 99;
Task t = Task.Run(() =>
{
System.Threading.Thread.Sleep(i * 5000);
z = 77;
});
// Output is always 99.
Console.WriteLine(String.Format("started thread {0}: {1}", i, z));
await t;
// Output is always 77.
Console.WriteLine(String.Format("finished thread {0}: {1}", i, z));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment