我见过很多类似的例子复制这个例子。他们中的大多数人表示他们正在使用Async CTP。我在Windows 8上使用Visual Studio 11,但不适用。如图所示,错误说TaskEx不存在。我想我错过了一个参考,但不知道哪一个。
此页面为http://users.zoominternet.net/~charleswatson/pic.png。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static Random rnd = new Random();
static void Main(string[] args)
{
//Do some other heavy duty background task in this thread
StartHotel();
Console.WriteLine("StartHotel called..");
Console.ReadLine();
}
static void StartHotel()
{
Console.WriteLine("Starting Hotel..");
for (int i = 0; i < 10; i++)
{
string name = "Chef" + i;
CookDish(name, "Dish" + i);
Console.WriteLine("Asked {0} to start cooking at {1}", name, DateTime.Now.ToString());
}
}
static async void CookDish(string chefName, string dish)
{
//Induce a random delay
int delay = rnd.Next(1000, 4000);
//Cook is cooking - Task
await TaskEx.Delay(delay);
//Write the result - StuffAfterAwait
Console.WriteLine("Chef {0} Finished at {1}", chefName, DateTime.Now.ToString());
}
}
}
只需右键单击 - >打开。图片通过css缩小。 – Femaref
@Femaref:啊,完美。谢谢 –
只需点击示例链接 –