Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return on Task<int>?

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.

like image 843
markzzz Avatar asked Jun 19 '18 08:06

markzzz


1 Answers

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);
}
like image 65
Patrick Hofman Avatar answered Sep 30 '22 06:09

Patrick Hofman