我这里有一些奇怪的问题。任务抛出的异常始终没有独立处理,我该如何尝试处理它。
我试试这个:
http://msdn.microsoft.com/en-us/library/dd997415%28v=vs.110%29.aspx http://msdn.microsoft.com/en-us/library/dd997415%28v=vs.110%29.aspx
private class MyCustomException : Exception
{
public MyCustomException(String message) : base(message)
{
}
}
public static void Main()
{
var task1 = Task.Factory.StartNew(() =>
{
throw new MyCustomException("I'm bad, but not too bad!");
});
try
{
task1.Wait();
}
catch (AggregateException ae)
{
// Assume we know what's going on with this particular exception.
// Rethrow anything else. AggregateException.Handle provides
// another way to express this. See later example.
foreach (var e in ae.InnerExceptions)
{
if (e is MyCustomException)
{
Console.WriteLine(e.Message);
}
else
{
throw;
}
}
}
Console.Read();
}
this:
http://dotnetcodr.com/2014/02/11/exception-handling-in-the-net-task-parallel-library-with-c-the-basics/ http://dotnetcodr.com/2014/02/11/exception-handling-in-the-net-task-parallel-library-with-c-the-basics/
this:
http://blogs.msdn.com/b/pfxteam/archive/2010/08/06/10046819.aspx http://blogs.msdn.com/b/pfxteam/archive/2010/08/06/10046819.aspx
this:
var task = Task.Factory.StartNew(() => this.InitializeViewModel(myViewModel));
task.ContinueWith(o => MyErrorHandler(task.Exception), TaskContinuationOptions.OnlyOnFaulted);
并在 StackOverflow 上查看许多其他类似的问题。但它总是一样的 - 异常不被处理。这些原始代码片段没有处理它!我觉得这里有某种魔力......
我从事 .Net Framework 4.0 工作
同时,处理对我有用的异常的单一方法是:
Task.Factory.StartNew(() =>
{
try
{
//do something that thrown exception
}
catch (Exception)
{
}
});