首页 > 解决方案 > 如何返回任务?

问题描述

我有这个代码:

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?
}

使用Taskasync/await。我想返回一个int作为任务的结果。我应该返回哪个对象?return 1;不会工作。

标签: c#async-awaittask

解决方案


您应该使用Task.FromResult, (并且不要使用Thread.Sleepfrom 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);
}

推荐阅读