私は作品のチェーンを作成します。彼らは私の追加のスレッドの内部で作業する必要があります。私はこの目的のためにTask
を使用します。また、例外が発生した場合にチェーンの作業を中断し、呼び出しスレッドにスローしたいと思います。しかし、チェーンが壊れていないことがわかりました。act2
とact3
も完成しました。例外が発生したときにタスクチェーンを壊す方法はありますか?
どうすれば修正できますか?あなたはNotOnFaultedタスク継続オプションを使用する必要が
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'や待ち時間のいずれかに直接アクセスする必要はありません。さらに、 'ContinueWith'を使用して、例外をチェックするためのタスクへのアクセスが必要な場合 - 例えば' ContinueWith(t => if(t.Faulted){..} else act3();) ' –
I本を介してthreads \ tasksで作業する方法を学ぶ。私はまだ 'async/await'については読まなかった。 –
'async/await'を使用したくない場合は、ContinueWithやTasFactory.StartNewやTask.Runなどを正しく使用する方法のドキュメント例を確認することをお勧めします。また、Task.ResultとTask.Wait()が何をしているかを確認します。タスクにフォールトが発生した場合にthrowします。あなたのコードははるかに複雑で、必要のない実装の内部を公開しようとします –