我从 here 复制了这个例子
我见过很多类似的例子。他们中的大多数人说他们正在使用异步 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());
}
}
}
最佳答案
在 CTP 中,我们无法向 Task
类型添加新功能,因此我们做了务实的事情,只是创建了一个新的 TaskEx
类型。在最终版本中不会有这样的类型;这些方法将像您期望的那样在 Task
上运行。
关于c# - 尝试了解 c# 中的新异步功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7576556/