類似しているが同じではないスレッドを見つけたので、重複していることが判明した場合はご容赦ください。タスク内でエラーを適切に「スロー」するにはどうすればよいですか。私はこのコードを持っています。条件が正しい場合、エラーがスローされますが、Visual Studio はそれが未処理であると不平を言います。しかし、その後、_LoadDataMappingFieldListError メソッドを含め、すべてが正常に実行されます。最初の ContinueWith で十分だと思いましたが、そうではないようです。テスト用と実際の取得用の 2 つの個別のタスクを実際に作成する必要がありますか? 少し冗長に思えます。コードは次のとおりです。
........
if (dcMapping.SettingsComplete().IsNullEmpty())
{
_TaskCanceller = new CancellationTokenSource();
_TaskLoader = Task<object>.Factory.StartNew(() =>
{
//Set the indicator and first test the connection to make sure it is working
IsLoadingDataMappingFieldList = true;
string test = dcMapping.TestConnection();
if (test.IsNotNullEmpty())
throw new DataConnectionException(test); // <--THE THROW IN QUESTION
return dcMapping.GetFieldNameList(); // <--VS BREAKS HERE SAYING THE ABOVE IS UNHANDLED
});
//If there is an error
_TaskLoader.ContinueWith(
antecendant => _LoadDataMappingFieldListError(antecendant.Exception),
_TaskCanceller.Token,
TaskContinuationOptions.OnlyOnFaulted,
TaskScheduler.FromCurrentSynchronizationContext());
//Set up receiving function
_TaskLoader.ContinueWith(
antecendant => _LoadDataMappingFieldListComplete((List<string>)antecendant.Result, RemapFields),
_TaskCanceller.Token,
TaskContinuationOptions.NotOnFaulted,
TaskScheduler.FromCurrentSynchronizationContext());
}
........