6

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.

markzzz
  • 47,390
  • 120
  • 299
  • 507
  • 10
    `return Task.FromResult(1)` More about [`Task.FromResult`](https://stackoverflow.com/questions/19568280/what-is-the-use-for-task-fromresulttresult-in-c-sharp) – CodeNotFound Jun 19 '18 at 08:53

1 Answers1

20

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);
}
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
  • Uhm. But how would Task.Delay(1000) be implemented so? Somethings like `public static Task Delay(int millisecondsDelay) { Thread.Sleep(millisecondsDelay); return Task.FromResult(1); }` I believe? – markzzz Jun 19 '18 at 09:13
  • 3
    Where did you get that nonsense from? The implementation is entirely different: https://referencesource.microsoft.com/#mscorlib/system/threading/Tasks/Task.cs,5863. – Patrick Hofman Jun 19 '18 at 09:19
  • "Nothing awaited: does the method need to be async?" - No, the OP's method wasn't `async`. – Enigmativity Jun 19 '18 at 09:25
  • 1
    The fact is: I need to do heavy operation within that function. Not using await inside anymore. If you see its not async that method. How would I do it? – markzzz Jun 19 '18 at 09:33
  • @Enigmativity Since `Thread.Sleep` might lock the main thread, I thought using `Task.Delay` with an `await` was a better option. Since it is unclear what OP wants to do, I thought I would give both options. – Patrick Hofman Jun 19 '18 at 11:16
  • @markzzz Then return `Task.FromResult(1)` as suggested in my answer. – Patrick Hofman Jun 19 '18 at 11:17
  • 2
    @PatrickHofman - My thought was that the OP put in `Thread.Sleep(1000);` just to simulate heavy work. – Enigmativity Jun 19 '18 at 11:19
  • Mine too, but what if he has an `async` method to call, just like `Task.Delay`, then there would be no need for `Task.FromResult`. @Enigmativity – Patrick Hofman Jun 19 '18 at 11:20