I'we got an async controller action with cancellation token as a parameter:
public async Task<ActionResult> Index(string NomenCode = "", string ProducerName = "", bool? WithAnalog = null, long? OrderId = null, CancellationToken cancelToken = default(CancellationToken))
{
// .. some code
// my async method gets this token
await SearchModel.GetRemains(search, NomenCode, ProducerName, _WithAnalog, this.HttpContext, cancelToken);
//.. more code
}
SearchModel.GetRemains
method calls 3 other async methods(web-services) and when one of them gets cancelled by a timeout, the others are not executing.
In every one of that 3 web services I connect to database also asyncronously. How can I make 2 of my async
tasks work when third one's async
child method gets an error?
I pass cancellation token parameter to all async
methods from the parent method.
And if I don't want a child action to effect on my parent action's execution at all? But want it to cancell if parent was cancelled? What should I do?
Thanks for your attention and help
How can I make 2 of my async tasks work when third one's async child method gets an error?
When a task is canceled or completes with an error (such as a timeout), then await
ing that task will raise an exception.
To avoid propagating the exception, just use try
/catch
:
try
{
await SearchModel.GetRemains(search, NomenCode, ProducerName, _WithAnalog, this.HttpContext, cancelToken);
}
catch (MyExpectedException)
{
...
}
But want it to cancell if parent was cancelled?
You are already passing the parent's CancellationToken
down, so this is already taken care of. The same cancellation token is shared between the parent and all of its children.