Skip to content

Instantly share code, notes, and snippets.

@radleta
Last active November 25, 2019 18:03
Show Gist options
  • Save radleta/8ec086962d829491166405ef28f7e08f to your computer and use it in GitHub Desktop.
Save radleta/8ec086962d829491166405ef28f7e08f to your computer and use it in GitHub Desktop.
C# Async vs Sync Examples
using System;
using System.Threading.Tasks;
using System.Threading;
using System.IO;
namespace AsyncTechTalk
{
class ProgramAsync
{
static int number = 0;
static async Task Main(string[] arg, CancellationToken cancellationToken)
{
var backgroundCancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(30));
var backgroundTask = Task.Run(() => Increment100Async(backgroundCancellationTokenSource.Token), backgroundCancellationTokenSource.Token);
while (!backgroundTask.IsCompleted)
{
Console.WriteLine($"Number: {number}");
await Task.Delay(1000, cancellationToken);
}
}
static async Task Increment100Async(System.Threading.CancellationToken cancellationToken)
{
while (number < 100)
{
//if (cancellationToken.IsCancellationRequested) return;
cancellationToken.ThrowIfCancellationRequested();
var amount = await ProgramAsync.GetDataFromDatabaseAsync(cancellationToken).ConfigureAwait(false);
number += amount;
}
}
static int GetDataFromDatabase()
{
System.Threading.Thread.Sleep(1000);
return 1;
}
static async Task<int> GetDataFromDatabaseAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
await Task.Delay(1000, cancellationToken).ConfigureAwait(false);
return 1;
}
static async Task<int> AddAsync(int y, int x, System.Threading.CancellationToken cancellationToken)
{
await Task.Delay(1000).ConfigureAwait(false);
return x + y;
}
static async Task<int> AddBadPerformanceAsync(int y, int x, System.Threading.CancellationToken cancellationToken)
{
if (y < 1) throw new ArgumentOutOfRangeException(nameof(y), y, "Cannot be less than one.");
return await AddAsync(x, y, cancellationToken).ConfigureAwait(false);
}
static Task<int> AddGoodPerformanceAsync(int y, int x, System.Threading.CancellationToken cancellationToken)
{
if (y < 1) throw new ArgumentOutOfRangeException(nameof(y), y, "Cannot be less than one.");
return AddAsync(y, x, cancellationToken);
}
static Task<int> AddCallingGoodPerformanceAsync(System.Threading.CancellationToken cancellationToken)
{
return AddGoodPerformanceAsync(1, 1, cancellationToken);
}
static Task<int> AddAntiPatternNoAwaitAsync(int y, int x, System.Threading.CancellationToken cancellationToken)
{
if (y < 1) throw new ArgumentOutOfRangeException(nameof(y), y, "Cannot be less than one.");
// BUG: Next line is anti-pattern and isn't properly executed b/c no await
AddAsync(y, x, cancellationToken);
return Task.FromResult(1);
}
static async Task<int> AddMustAwaitAsync(int y, int x, System.Threading.CancellationToken cancellationToken)
{
if (y < 1) throw new ArgumentOutOfRangeException(nameof(y), y, "Cannot be less than one.");
var z = await AddAsync(x, y, cancellationToken).ConfigureAwait(false);
z *= 2;
return z;
}
static Task<int> AddAntiPatternUsingAsync(System.Threading.CancellationToken cancellationToken)
{
using (var file = System.IO.File.Open("data.txt", System.IO.FileMode.Open))
{
return WriteAsync(file, cancellationToken);
}
}
static async Task<int> AddCorrectUsingAsync(int y, int x, System.Threading.CancellationToken cancellationToken)
{
if (y < 1) throw new ArgumentOutOfRangeException(nameof(y), y, "Cannot be less than one.");
using (var file = System.IO.File.Open("data.txt", System.IO.FileMode.Open))
{
return await WriteAsync(file, cancellationToken).ConfigureAwait(false);
}
}
private static Task<int> WriteAsync(FileStream file, CancellationToken cancellationToken)
{
//file.Write();
throw new NotImplementedException();
}
private static int WriteSync(FileStream file)
{
//file.Write();
throw new NotImplementedException();
}
static Task AntiPatternTryAsync(System.Threading.CancellationToken cancellationToken)
{
try
{
return Task.Delay(1000, cancellationToken);
}
catch
{
// log it and keep going
return Task.CompletedTask;
}
finally
{
// do something else
var i = 0;
i++;
}
}
static async Task CorrectPatternTryAsync(System.Threading.CancellationToken cancellationToken)
{
try
{
await Task.Delay(1000, cancellationToken).ConfigureAwait(false);
}
catch
{
// log it and keep going
}
finally
{
// do something else
var i = 0;
i++;
}
}
static Task<int> MultiplyAsync(int x, int y, System.Threading.CancellationToken cancellationToken)
{
// no calling another async method
var z = x * y;
return Task.FromResult(z);
}
static Task SyncMethodAntiPatternAsync(int x, System.Threading.CancellationToken cancellationToken)
{
// no calling another async method
Console.WriteLine(x);
return Task.FromResult(x);
}
static Task SyncMethodCorrectPatternAsync(int x, System.Threading.CancellationToken cancellationToken)
{
// no calling another async method
Console.WriteLine(x);
return Task.CompletedTask;
}
}
}
using System;
using System.Threading.Tasks;
namespace AsyncTechTalk
{
class ProgramSync
{
static int number = 0;
static void Main(string[] args)
{
var backgroundTask = Task.Run(IncrementSync);
while (!backgroundTask.IsCompleted)
{
Console.WriteLine($"Number: {number}");
System.Threading.Thread.Sleep(1000);
}
}
static void IncrementSync()
{
while (number < 100)
{
var amount = GetDataFromDatabaseSync();
number += amount;
}
}
static int GetDataFromDatabaseSync()
{
System.Threading.Thread.Sleep(1000);
return 1;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment