c# - 使用非阻塞任务
问题描述
以下代码返回不正确的产品。我希望我需要在我的 AsyncMultiply 函数中使用 await 术语,我尝试将它添加到所有行的前面,但它不起作用。如何修复代码以使任务成为非阻塞、正确计算的任务?
using System;
using System.Threading;
using System.Threading.Tasks;
namespace NonBlockingTasks
{
class Program
{
static int prod;
public static void Main(string[] args)
{
Task.Run(async () => { await AsyncMultiply(2, 3); });
for(int i = 0; i < 10; i++) {
Console.Write(i + " ");
Thread.Sleep(100);
}
Console.WriteLine();
Console.WriteLine("Prod = " + prod);
Console.Write("Press any key to continue . . . ");
Console.ReadKey();
}
public static async Task DoSomethingAsync()
{
await Task.Delay(100);
}
public static async Task<int> AsyncMultiply(int a, int b)
{
Thread.Sleep(2000);
prod = a * b;
return prod;
}
}
}
解决方案
Task.Run 返回一个任务,您无需等待它完成。如果您使用的是 C# 7.1 (.net 4.7) 或更高版本,您可以将等待的对象一直显示给调用者:
static int prod;
public static async Task Main(string[] args)
{
Task running = Task.Run(async () => { await AsyncMultiply(2, 3); });
for (int i = 0; i < 10; i++)
{
Console.Write(i + " ");
Thread.Sleep(100);
}
await running; // Wait for the previously abandoned task to run.
Console.WriteLine();
Console.WriteLine("Prod = " + prod);
Console.Write("Press any key to continue . . . ");
Console.ReadKey();
}
public static async Task DoSomethingAsync()
{
await Task.Delay(100);
}
public static async Task<int> AsyncMultiply(int a, int b)
{
Thread.Sleep(2000);
prod = a * b;
return prod;
}
否则,您可以冻结当前线程,等待任务完成:
static int prod;
public static void Main(string[] args)
{
Task running = Task.Run(async () => { await AsyncMultiply(2, 3); });
for (int i = 0; i < 10; i++)
{
Console.Write(i + " ");
Thread.Sleep(100);
}
running.Wait(); // Freeze thread and wait for task.
Console.WriteLine();
Console.WriteLine("Prod = " + prod);
Console.Write("Press any key to continue . . . ");
Console.ReadKey();
}
public static async Task DoSomethingAsync()
{
await Task.Delay(100);
}
public static async Task<int> AsyncMultiply(int a, int b)
{
Thread.Sleep(2000);
prod = a * b;
return prod;
}
推荐阅读
- ios - Firebase 中的大量图片
- java - 无法解析构造函数 'ArrayAdapter(匿名 android.widget.SeekBar.OnSeekBarChangeListener,int,java.util.ArrayList
) - sql - 当更新条件取决于另一个表的值时如何更新表中的列
- laravel - Laravel 5.6 中 RedirectIfAuthenticated 的逻辑是什么?
- ruby-on-rails - 如何阻止 Gemfile.lock 文件自动一次又一次地更改?
- python - ImageDataGenerator 是如何工作的?它会自动重新调整输入吗?
- reactjs - 登录成功反应redux时不重定向到HOC中传递的组件
- regex - 如何制作一个检查所有第一个字母都应该是大写的模式?
- python - 使用 Flask API,如何使用浏览器/客户端的 jwt_required 装饰器从服务器上传和下载文件?
- bash - tar 在磁盘已满时返回成功状态