我創建了作品鏈。他們將在我的附加線程內工作。爲此我使用Task
。另外,如果發生任何異常並將其放入調用線程中,我想要中斷鏈的工作。但我看到我的鏈條沒有損壞,並且act3
的act2
也完成了。如何在發生異常時中斷任務鏈?
我該如何解決?
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();
}
}
}
爲什麼不直接使用'async/await'?你不需要'Task.Start'或直接訪問awaiter。此外,如果您想使用'ContinueWith',您*需要*訪問任務以檢查異常,例如 - 'ContinueWith(t => if(t.Faulted){..} else act3();)' –
I學會通過一本書來處理線索\任務。我仍然沒有讀到'async/await'。 –
我建議你查看關於如何正確使用的文檔示例,如ContinueWith和TasFactory.StartNew或Task.Run,如果你不想使用'async/await'。還要檢查Task.Result和Task.Wait()是做什麼的 - 它們會在任務出現故障時拋出。你的代碼太複雜了,並且試圖暴露實現內部結構,它只是不需要 –