Created
December 20, 2015 08:10
-
-
Save BojanKomazec/f642e1d7f1efcda48f3c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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