Skip to content

Instantly share code, notes, and snippets.

@BojanKomazec
Created December 20, 2015 08:10
Show Gist options
  • Save BojanKomazec/f642e1d7f1efcda48f3c to your computer and use it in GitHub Desktop.
Save BojanKomazec/f642e1d7f1efcda48f3c to your computer and use it in GitHub Desktop.
using System;
using System.Threading;
using System.Threading.Tasks;
public class Program
{
public static void Main()
{
Program.MainAsync().Wait();
}
private static async Task MainAsync()
{
var myService = new MyService();
var cancellationTokenSource = new CancellationTokenSource();
var token = cancellationTokenSource.Token;
var task = myService.SomeLongOperation(token);
cancellationTokenSource.CancelAfter(1000);
try
{
await task;
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
Console.WriteLine($"Task.IsCanceled: {task.IsCanceled}");
Console.WriteLine($"Task.IsFaulted: {task.IsFaulted}");
Console.WriteLine($"Task.Exception: {((task.Exception == null) ? "null" : task.Exception.ToString())}");
}
}
}
public interface IMyService
{
Task SomeLongOperation(CancellationToken cancellationToken);
}
public class MyService : IMyService
{
public async Task SomeLongOperation(CancellationToken cancellationToken)
{
for(var i = 0; i < 100; i++)
{
Console.Write(".");
await Task.Delay(100);
cancellationToken.ThrowIfCancellationRequested();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment