Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# “任务并行库异常句柄”;一项任务被取消;_C#_Multithreading_C# 4.0_.net 4.0_Task Parallel Library - Fatal编程技术网

C# “任务并行库异常句柄”;一项任务被取消;

C# “任务并行库异常句柄”;一项任务被取消;,c#,multithreading,c#-4.0,.net-4.0,task-parallel-library,C#,Multithreading,C# 4.0,.net 4.0,Task Parallel Library,我有一个方法: var taskCount = Task<List<Client>>.Factory.StartNew(() => { return ClientRepository.GetListAll(); }).LogExceptions<Client>(); count = taskCount.Result; var taskCou

我有一个方法:

var taskCount = Task<List<Client>>.Factory.StartNew(() =>
                            {

return ClientRepository.GetListAll();
                            }).LogExceptions<Client>();
count = taskCount.Result;
var taskCount=Task.Factory.StartNew(()=>
{
return ClientRepository.GetListAll();
}).LogExceptions();
count=taskCount.Result;
我的扩展方法为LogException,如下所示:

public static Task<T> LogExceptions<T>(this Task<T> task) where T : new()
        {
            return task.ContinueWith<T>((antecedent) =>
            {
                bool isError = false;
                var aggException = antecedent.Exception.Flatten();
                foreach (var exception in aggException.InnerExceptions)
                {
                    isError = true;
                    LogWrite.LogStep(" Task Exception - ", exception.Message);
                }
                if (isError)
                {
                    return new T();
                }
                else
                {
                    return antecedent.Result;
                }
            },
            TaskContinuationOptions.OnlyOnFaulted);
        }
公共静态任务日志异常(此任务),其中T:new()
{
返回任务。继续((先行项)=>
{
bool-isError=false;
var aggException=antecedent.Exception.flant();
foreach(aggException.InnerExceptions中的var异常)
{
isError=真;
LogWrite.LogStep(“任务异常-”,异常消息);
}
如果(isError)
{
返回新的T();
}
其他的
{
返回先行结果;
}
},
TaskContinuationOptions.OnlyOnFaulted);
}
如果发生任何异常,上面的代码工作正常,它将处理异常并防止工作进程关闭它

但当没有错误时,它只是返回聚合异常作为“任务被取消”。不确定我在上面的代码中做错了什么


如果上述代码错误,那么以通用方式处理任务异常的最佳方法是什么。

问题在于您在继续中选择了
TaskContinuationOptions
OnlyOnFaulted。Per,
OnlyOnFaulted
表示只有在前面的任务引发未处理的异常时,才会继续。由于在所有情况下都不会出现异常,因此继续操作无法正常工作。尝试忽略
TaskContinuationOptions
参数,或使用默认枚举值
None

您可以检查聚合异常的内部异常吗?啊,我知道了。。谢谢你救了我的命。。如果我删除了TaskContinuationOption,一切都会很好,而且也很有意义。。至少我对TaskContinuationOption的理解现在很清楚了…High five:)…我无法投票给你的答案,因为我需要15个声誉,而且我是这个社区的新手。但这确实是一个很好的答案,我相信有很多人可能会像我一样面对这个问题。以前没有人在stack exchange中解释过,或者可能是我在发布此问题之前搜索时没有找到任何答案…你是最好的。。