Skip to content

Instantly share code, notes, and snippets.

@demonixis
Created August 31, 2017 14:13
Show Gist options
  • Save demonixis/59ccaf97f30e914b1174dfdcdda3ec18 to your computer and use it in GitHub Desktop.
Save demonixis/59ccaf97f30e914b1174dfdcdda3ec18 to your computer and use it in GitHub Desktop.
Implementation example of a Task with C# 5+
using System;
using System.Threading.Tasks;
namespace ConsoleApp1
{
public class AsyncProcessTest
{
// This function is going to start an expensive process.
// Thanks to async/await the main Thread will not be blocked!
public async void Initialize()
{
Console.WriteLine("Starting The Expensive Process...");
var number = await CalculateThingsAsync();
Console.WriteLine($"The result is {number}");
}
// The Task will returns an integer when it's done.
public async Task<int> CalculateThingsAsync()
{
var task = Task.Run(() => DoExpensiveProcess());
return await task;
}
// The expensive process.
private int DoExpensiveProcess()
{
var counter = 0;
for (var i = 0; i < int.MaxValue; i++)
counter++;
return counter;
}
}
class Program
{
// Entry Point.
static void Main(string[] args)
{
// Start the example.
var p = new AsyncProcessTest();
p.Initialize();
Console.ReadKey();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment