请考虑以下事项:
Add-Type @'
public class Thrower
{
public string Throw()
{
throw new System.Exception("some exception");
return "return value";
}
public System.Func<string> GetThrow
{
get { return Throw; }
}
}
'@ -IgnoreWarnings
$t = [System.Threading.Tasks.Task[string]]::new([Thrower]::new().GetThrow)
$t.Start()
documentation for the Task<TResult>.Result
property包括以下声明:
请注意,如果在任务操作期间发生异常,或者任务已被取消,则Result属性不会返回值。相反,尝试访问属性值会抛出AggregateException异常。
基于此,我希望访问$t.Result
会引发异常。它不是。但是,请调用
try { $t.get_Result() } catch { throw $_.Exception.InnerException.InnerException }
输出
some exception
At line:1 char:37
+ ... Result() } catch { throw $_.Exception.InnerException.InnerException }
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], Exception
+ FullyQualifiedErrorId : some exception
同样,调用
try { $t.Wait() } catch { throw $_.Exception.InnerException.InnerException }
输出相同的异常。
the analogous program in C#的粗略测试似乎表明访问Task<TResult>.Result
确实在C#中引发了异常。
为什么在Task<TResult>.Result
和.get_Result()
执行时,不在PowerShell中访问.Wait()
会抛出异常?