The design of the upcoming C# 8 IAsyncEnumerable
uses ValueTask
and ValueTask<T>
to communicate the potentially synchronous results back to the consumer logic. They both have the IsFaulted
property, but unlike Task
, there is no Exception
property.
Is it even possible to have a ValueTask
that doesn't hold a normal Task
and is in the faulted or canceled state?
The ValueTask<T>.Result
's documentation indicates calling it on a failed task will rethrow the contained Exception
. Would the following code make thus sense to extract the Exception
?
IAsyncEnumerable<int> asyncSequence = ...
ValueTask<bool> valueTask = asyncSequence.MoveNextAsync();
if (valueTask.IsFaulted) {
// this has to work in a non-async method
// there is no reason to block here or use the
// async keyword
try {
var x = valueTask.Result;
} catch (Exception ex) {
// work with the exception
}
}
ValueTask endTask = asyncSequence.DisposeAsync();
if (endTask.IsFaulted) {
// there is no ValueTask.Result property
// so the appoach above can't work
}
The non-generic ValueTask
does not have a Result
property. How can I extract the Exception
then?
Generally, I suppose applying AsTask
could be used for both extractions, however, I'd think it incurs allocation making the use of ValueTask
questionable in the first place as I understand it.