c# - 如何返回任务?
问题描述
我有这个代码:
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?
}
使用Task
和async/await
。我想返回一个int
作为任务的结果。我应该返回哪个对象?return 1;
不会工作。
解决方案
您应该使用Task.FromResult
, (并且不要使用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);
}
推荐阅读
- c# - .rdlc 本地处理异常中的打印问题
- security - 通过 Jenkins 的 HTTP 主机中毒漏洞进行未经授权的 URL 重定向
- python-3.x - 如果任何实例处于活动状态,它在两种情况下都响应是
- ssl-certificate - 有没有办法在 Ubuntu 18 或更高版本中安装 pkcs12 (p12) 证书?
- sql - pyspark中的分组索引
- swift - iOS 14 MapKit 选择注释图像错误
- html - 点击链接后不清除查询参数
- javascript - 在 JavaScript 中是否有类似可选链接的赋值
- email - 电子邮件中的 MIME 多部分
- azure - 如何将 ASP.NET Core 项目部署到 Azure?