I create the chain of the works. They are to work inside of my additional thread. I use the Task
for this purpose. Also, I want to break the chain's work if any exception occurred and throw it in the calling thread. But I see my chain wasn't broken and the act2
with act3
was completed too.
How can I fix it?
using System;
using System.Threading.Tasks;
namespace Bushman.Sandbox.Threads {
class Program {
static void Main(string[] args) {
Console.Title = "Custom thread";
try {
// First work
Action act1 = () => {
for (int i = 0; i < 5; i++) {
// I throw the exeption here
if (i == 3) throw new Exception("Oops!!!");
Console.WriteLine("Do first work");
}
};
// Second work
Action act2 = () => {
for (int i = 0; i < 5; i++)
Console.WriteLine(" Do second work");
};
// Third work
Func<int> act3 = () => {
for (int i = 0; i < 5; i++)
Console.WriteLine(" Do third work");
return 12345;
};
Task task = new Task(act1);
// Build the chain of the works
var awaiter = task.ContinueWith(_ => act2(),
TaskContinuationOptions.ExecuteSynchronously)
.ContinueWith(_ => act3(),
TaskContinuationOptions.ExecuteSynchronously)
.GetAwaiter();
Console.WriteLine("Work started...");
// launch the chain
task.Start();
// Here I get some result
int result = awaiter.GetResult(); // 12345
if (task.IsCanceled || task.IsFaulted) {
throw task.Exception.InnerException;
}
Console.WriteLine("The result: {0}",
result.ToString());
}
catch (Exception ex) {
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(ex.Message);
Console.ResetColor();
}
Console.WriteLine("Press any key for exit...");
Console.ReadKey();
}
}
}
You have to use the NotOnFaulted Task Continuation Option.
Since TaskContinuationOptions is decorated with the Flags attribute, you can combine NotFaulted with other options.
Even if you are using the async/await keywords, this approach is still valid (but you get rid of GetAwaiter call)