I have the following code:
//Await #1
var response1 = await doSomething();
if(response1.isSuccess) {
//Await #2
var response2 = await doSomethingElse();
}
Response 1 and response 2 are totally independent and i want to parallelize the await task here. Basically response 2 takes a lot of time and hence is only invoked when response1 is success. Is there any way in which i can invoke both tasks and see the result of response 1 and if it is fail, i drop/skip the response of Await#2.
If you don't await the task or explicitly check for exceptions, the exception is lost. If you await the task, its exception is rethrown. As a best practice, you should always await the call. By default, this message is a warning.
The await keyword, by contrast, is non-blocking, which means the current thread is free to do other things during the wait.
The await operator suspends evaluation of the enclosing async method until the asynchronous operation represented by its operand completes. When the asynchronous operation completes, the await operator returns the result of the operation, if any.
Delay will create a task which will complete after a time delay. Task. Delay is not blocking the calling thread so the UI will remain responsive.
Essentially what you want is to cancel a task, but with a little more logic.
You need to edit doSomethingElse
so that it accepts a CancellationToken
, and also so that it makes use of it to stop what its doing:
public async Task<Foo> DoSomethingElse(CancellationToken token) {
...
if (token.IsCancellationRequested) {
// stop what you are doing...
// I can't tell you how to implement this without seeing how DoSomethingElse is implemented
}
...
}
Now, get a CancellationToken
from a CancellationTokenSource
:
var source = new CancellationTokenSource();
var token = source.Token;
And here comes the logic of "if response 1 fails cancel response 2":
var response2Task = DoSomethingElse(token);
var response1 = await DoSomething();
if (!response1.IsSuccess) {
source.Cancel();
} else {
var response2 = await response2Task;
}
var task2 = doSomethingElse();
var response1 = await doSomething();
if(response1.isSuccess) {
var response2 = await task2;
}
This will start the execution of doSomethingElse()
immediately, and only wait for its completion when response1.isSuccess == true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With