我发现线程相似但不相同,如果结果是重复的,请原谅我。如何在任务中正确“抛出”错误。我有这段代码,当条件合适时,它会抛出错误,但 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());
}
........