Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Skip the await task response conditional

Tags:

c#

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.

like image 748
Shubham Avatar asked Dec 24 '19 09:12

Shubham


People also ask

What happens if you dont await a Task?

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.

Is await blocking C#?

The await keyword, by contrast, is non-blocking, which means the current thread is free to do other things during the wait.

What is Awaitable in C#?

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.

Does await Task delay block thread?

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.


2 Answers

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;
}
like image 154
Sweeper Avatar answered Oct 05 '22 23:10

Sweeper


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

like image 20
Piotr L Avatar answered Oct 05 '22 23:10

Piotr L