我正在学习如何在编程中做异步和等待工作.我在互联网上看到了这个例子,上面说这是异步代码:
class Program
{
static async Task Main(string[] args)
{
Method2();
var count = await Method1();
Method3(count);
Console.ReadKey();
}
static async Task<int> Method1()
{
int count = 0;
await Task.Run(() =>
{
for (int i = 0; i < 3; i++)
{
Console.WriteLine(" Method 1");
count += 1;
}
});
return count;
}
static void Method2()
{
for (int i = 0; i < 3; i++)
{
Console.WriteLine(" Method 2");
}
}
static void Method3(int count)
{
Console.WriteLine("Total count is " + count);
}
}
据我所知,异步编程是并发编程的一种形式,它允许两段独立的代码同时运行.但所有这些等待操作符都会使代码一致运行,实际上,我们可以使用以下示例,它会给出相同的输出:
class Program
{
static async Task Main(string[] args)
{
Method2();
Method3(Method1());
Console.ReadKey();
}
static int Method1()
{
int count = 0;
for (int i = 0; i < 3; i++)
{
Console.WriteLine(" Method 1");
count += 1;
}
return count;
}
static void Method2()
{
for (int i = 0; i < 3; i++)
{
Console.WriteLine(" Method 2");
}
}
static void Method3(int count)
{
Console.WriteLine("Total count is " + count);
}
}
那么,当等待操作符实际上使异步代码同步时,我为什么要使用它们呢?