0

I have 2 async functions that I execute and return an integer. When I try to access the return value, the IDE complains that the tasks are void type, not int type.

private async Task<int> func01(int _i1, int _i2)
{
    return await Task.Run(async () => {                
            await Task.Delay(1000);
            return 1;
        });

}

private async Task<int> func02(string _i1, string_i2)
{
    return await Task.Run(async () => {                
            await Task.Delay(3000);
            return 1;
        });

}

Task _t1 = func01(1, 3);
Task _t2 = func02("Hello", "World");
int _r1 = await _t1; //here, IDE says that _t1 and _t2 are void types
int _r2 = await _t2;

How do I return a value from an async task?

1
  • 5
    You are upcasting the return values of the functions to Task instead of Task<int> Commented Apr 21, 2022 at 20:08

1 Answer 1

6

Because return type of functions are not Task, its return Task<int>. So you have to use;

Task<int> _t1 = func01(1, 3);
Task<int> _t2 = func02("Hello", "World");

Tip: You can also use var keyword. I think its better.

var _t1 = func01(1, 3);
var _t2 = func02("Hello", "World");
Sign up to request clarification or add additional context in comments.

2 Comments

var will work too. I personally prefer declaring all local variables as var
I update answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.