我试图了解如何使用.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 …
Run Code Online (Sandbox Code Playgroud)