Last active
March 7, 2020 12:04
-
-
Save FrankKerrigan/bba05009e0dd8e851916cfa98c6f46b2 to your computer and use it in GitHub Desktop.
Task error handling C#
This file contains 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.Collections.Generic; | |
using System.Threading.Tasks; | |
namespace Yield | |
{ | |
class Program | |
{ | |
//This is not real code only an example | |
static void Main(string[] args) | |
{ | |
DoTasks(); | |
} | |
static void DoTasks() | |
{ | |
// Run Stuff in BackGround | |
Task.Factory.StartNew(() => | |
{ | |
//Do this in the background | |
SomeIntensiveJob(); | |
}).ContinueWith(task => | |
{ | |
//Check to see if there was a exception on the task handle it. | |
if (task.IsFaulted) | |
{ | |
string exMessage = "unknown error"; | |
string exStack = "unknow Exception is null"; | |
if (task.Exception != null) | |
{ | |
//Log all the Exceptions (maybe lots) | |
foreach (var ex in task.Exception.InnerExceptions) | |
{ | |
exMessage = ex.Message; | |
exStack = ex.StackTrace; | |
string errlog = $"Stuff , Exception : {exMessage} , Stack : {exStack} "; | |
Console.WriteLine(errlog); | |
} | |
} | |
Console.WriteLine( $"Error on stuff {exMessage}, with stack {exStack}"); | |
return; // exit on error | |
} ////////////////////////// end exception handling /////////////////////////////////// | |
// do this on the UI thread once the task has finished.. | |
// The task has completed without any issues so do your stuff | |
runPostTaksStuff(); | |
}, System.Threading.CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.FromCurrentSynchronizationContext()); | |
} | |
private static void runPostTaksStuff() | |
{ | |
throw new NotImplementedException(); | |
} | |
private static void SomeIntensiveJob() | |
{ | |
throw new NotImplementedException(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment