如何从异步任务返回结果?

时间:2015-10-20 10:47:29

标签: c# async-await

我想从异步任务返回字符串结果。

System.Threading.Tasks.Task.Run(async () => await audatex.UploadInvoice(assessment, fileName));

public async Task UploadInvoice(string assessment, string fileName)
{
    //Do stuff
    return string;
}

异步编程让我困惑,有人可以解释一下吗?

4 个答案:

答案 0 :(得分:22)

异步编程可能需要一段时间才能解决问题,所以我会发布对我有用的内容,以防它帮助其他任何人。

如果要将业务逻辑与异步代码分开,可以使UploadInvoice方法保持无异步:

private string UploadInvoice(string assessment, string filename)
{
    // Do stuff    
    Thread.Sleep(5000);

    return "55";
}

然后你可以创建一个异步包装器:

private async Task<string> UploadInvoiceAsync(string assessment, string filename)
{
    return await Task.Run(() => UploadInvoice(assessment, filename));
}

给你选择致电:

public async Task CallFromAsync()
{
    string blockingInvoiceId = UploadInvoice("assessment1", "filename");

    string asyncInvoiceId = await UploadInvoiceAsync("assessment1", "filename");
}

有时您可能需要从非异步方法调用异步方法。

// Call the async method from a non-async method
public void CallFromNonAsync()
{
    string blockingInvoiceId = UploadInvoice("assessment1", "filename");

    Task<string> task = Task.Run(async () => await UploadInvoiceAsync("assessment1", "filename"));
    task.Wait();
    string invoiceIdAsync = task.Result;
}

----编辑:添加更多示例,因为人们发现这很有用----

有时您希望等待任务,或者在完成时使用方法继续执行任务。这是一个可以在控制台应用程序中运行的工作示例。

    class Program
    {
        static void Main(string[] args)
        {
            var program = new Program();
            program.Run();
            Console.ReadKey();
        }

        async void Run()
        {
            // Example 1
            Console.WriteLine("#1: Upload invoice synchronously");
            var receipt = UploadInvoice("1");
            Console.WriteLine("Upload #1 Completed!");
            Console.WriteLine();

            // Example 2
            Console.WriteLine("#2: Upload invoice asynchronously, do stuff while you wait");
            var upload = UploadInvoiceAsync("2");
            while (!upload.IsCompleted)
            {
                // Do stuff while you wait
                Console.WriteLine("...waiting");
                Thread.Sleep(900);
            }
            Console.WriteLine("Upload #2 Completed!");
            Console.WriteLine();

            // Example 3
            Console.WriteLine("#3: Wait on async upload");
            await UploadInvoiceAsync("3");
            Console.WriteLine("Upload #3 Completed!");
            Console.WriteLine();

            // Example 4
            var upload4 = UploadInvoiceAsync("4").ContinueWith<string>(AfterUploadInvoice);
        }

        string AfterUploadInvoice(Task<string> input)
        {
            Console.WriteLine(string.Format("Invoice receipt {0} handled.", input.Result));
            return input.Result;
        }

        string UploadInvoice(string id)
        {
            Console.WriteLine(string.Format("Uploading invoice {0}...", id));
            Thread.Sleep(2000);
            Console.WriteLine(string.Format("Invoice {0} Uploaded!", id));
            return string.Format("<{0}:RECEIPT>", id); ;
        }

        Task<string> UploadInvoiceAsync(string id)
        {
            return Task.Run(() => UploadInvoice(id));
        }
    }

答案 1 :(得分:18)

您的方法应该返回Task<string>,而不是Task

public async Task<string> UploadInvoice(string assessment, string fileName)
{
    //Do stuff
    return string;
}

答案 2 :(得分:3)

这样做:

public async Task<string> UploadInvoice(string assessment, string fileName)

然后await结果:

string result = await UploadInvoice("", "");

此处可以看到更多示例:

Async Return Types

答案 3 :(得分:0)

public async Task<string> UploadInvoice(string assessment, string fileName)
{
    string result = GetResultString();//Do stuff    
    return Task.FromResult(result);
}