我正在尝试理解如何使用.NET 4.5的async/await关键字来处理本质上是同步的任务。例如,某种复杂的数学计算。在下面的示例中,我使用了Thread.Sleep来模拟这个操作。我的问题是,是否有一种方法可以使这样的方法像异步方法一样运行?如果没有,你是否只需要像ThisWillRunAsyncTest方法中所做的那样,在该同步方法上执行类似于Task.Factory.StartNew的操作。有没有更简洁的方法?
using System.Threading;
using System.Collections.Generic;
using System.Threading.Tasks;
using NUnit.Framework;
[TestFixture]
public class AsyncAwaitTest
{
[Test]
//This test will take 1 second to run because it runs asynchronously
//Is there a better way to start up a synchronous task and have it run in parallel.
public async void ThisWillRunAsyncTest()
{
var tasks = new List<Task>();
for (int i = 0; i < 5; i++)
{
tasks.Add(Task.Factory.StartNew(() => this.RunTask()));
}
await Task.WhenAll(tasks);
}
[Test]
//This test will take 5 seconds to run because it runs synchronously.
//If the Run Task had an await in it, this this would run synchronously.
public async void ThisWillRunSyncTest()
{
var tasks = new List<Task>();
for (int i = 0; i < 5; i++)
{
tasks.Add(this.RunTask());
}
await Task.WhenAll(tasks);
}
//This is just an example of some synchronous task that I want to run in parallel.
//Is there something I can do in this method that makes the async keyword work? I.e. this would run asynchronously when called from ThisWillRunSyncTest
public async Task RunTask()
{
Thread.Sleep(1000);
}
}
RunTask
是同步的,那么它根本不应该返回一个Task
,而将其转换为任务应该由调用者完成。 - Lee