Async expects to receive an exception from the result of an internal task

Given the following snippet:

public Task StartReading()
{
  var activityCheck = Task.Factory.StartNew(async () => await this.CheckActivityTimeout(), this._token.Token).Unwrap();
  var reading = Task.Factory.StartNew(async () => await this.ReadAsync(), this._token.Token).Unwrap();

  // for reference, this code produces the same result:
  // var activityCheck = this.CheckActivityTimeout();
  // var reading = this.ReadAsync();

  return Task.WhenAny(reading, activityCheck);
}

When an exception is thrown at CheckActivityTimeout, I will catch it as follows.

var read = StartReading()
var tasks = new Task[] { read, taskx, tasky, taskz };
int completed = Task.WaitAny(tasks);
var r = tasks[completed];

rdoes not have this set of exceptions. Instead, when I look at the debugger, I find that the task rhas an exception stored in the property Result. How do I get to this actual result?

r has type Id = 17, Status = RanToCompletion, Method = "{null}", Result = "System.Threading.Tasks.UnwrapPromise``1[System.Threading.Tasks.TaskExtensions+VoidResult]"

You can see that the actual exception is inside the result of the internal task. How do I push it up?

r.Exception == null
r.Result not available.

Update

var r = Task.WhenAny(tasks).Result; // produces exactly the same wrapped result!

In the debugger, it looks like this:

enter image description here

+4
source share
2 answers

, Task.WhenAny. Task.WhenAny , . read.Result - , , , .

, , , StartReading , " ", :

public async Task StartReadingAsync()
{
  var activityCheck = this.CheckActivityTimeout();
  var reading = this.ReadAsync();
  await await Task.WhenAny(reading, activityCheck);
}

StartNew. CPU ( ), , Task.Run; .

+6

, - Task<Task>

Task.WhenAny .

 var result = Task.WhenAny(reading, activityCheck).Result;
var inner = ((Task<Task>)result).Result;
inner.Exception...
-1

Source: https://habr.com/ru/post/1627290/


All Articles