gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 08:14:11 24 4
gpt4 key购买 nike

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

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

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

异步编程让我很困惑,谁能解释一下?

最佳答案

异步编程可能需要一段时间才能让您理解,所以我会发布对我有用的内容,以防对其他人有所帮助。

如果您想将业务逻辑与异步代码分开,您可以让您的 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 = UploadInvoiceAsync("assessment1", "filename");
string invoiceIdAsync = task.GetAwaiter().GetResult();
}

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

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

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));
}
}

关于c# - 如何从异步任务返回结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33234614/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com