我学会了Task
比async
/更容易使用await
。现在,我正在尝试使用Task
来学习async
/ await
。
static void Main(string[] args)
{
Console.ReadKey(true);
//Magic1();
Magic2();
Console.WriteLine("{0}", DateTime.Now.ToString());
Console.ReadKey(true);
}
static async void Magic1()
{
var taskA = GetDataAsync();
var taskB = GetDataAsync();
var taskC = GetDataAsync();
Console.WriteLine("a: " + await taskA);
Console.WriteLine("b: " + await taskB);
Console.WriteLine("c: " + await taskC);
}
static Task Magic2()
{
return Task.Run(() =>
{
var taskA = GetDataAsync();
var taskB = GetDataAsync();
var taskC = GetDataAsync();
Task.WaitAll(new Task[] { taskA, taskB, taskC });
Console.WriteLine("a: " + taskA.Result);
Console.WriteLine("b: " + taskB.Result);
Console.WriteLine("c: " + taskC.Result);
});
}
static Task<string> GetDataAsync()
{
return Task.Run(() =>
{
var startTime = DateTime.Now;
for (var i = 0; i < 1000000000; i++)
{
}
var endTime = DateTime.Now;
return startTime.ToString() + " to " + endTime.ToString() + " is " + (endTime - startTime).ToString();
});
}
我创建了两种似乎做同样事情的方法,我的问题是:
1)在引擎盖下是一样的吗Magic1
?Magic2
2)如果它们不一样,我可以转换为不使用和关键字Magic1
做同样事情的方法吗?async
await