I've this code:
static void Main(string[] args)
{
// start import process
Task<int> task = StartImportProcess();
task.Wait();
// check result
// process finished
Console.ReadKey();
}
static async Task<int> StartImportProcess()
{
int result = 0;
result = await ImportCustomers();
// some other async/await operations
return result;
}
static Task<int> ImportCustomers()
{
// some heavy operations
Thread.Sleep(1000);
return 1; // <<< what should I return?
}
Using Task
and async/await
. I'd like to return an int
as result of the task. Which object whould I return? return 1;
won't work.
You should use Task.FromResult
, (and don't use Thread.Sleep
from a Task
):
static async Task<int> ImportCustomers()
{
// some heavy operations
await Task.Delay(1000);
// Already awaited, so we can return the result as-is.
return 1;
// Or: if not already awaited anything,
// and also with non-async tasks, use:
return Task.FromResult(1);
}
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