【发布时间】:2016-03-09 07:26:59
【问题描述】:
我正在为我的项目对async 和await 进行研发。我了解到的是,当调用async 方法时,它会释放线程并让线程被其他人使用。我们可以使用 await 关键字为 await-able 方法设置回调,并且该方法在结果准备好时返回值。如果发生这种情况:
- 我们应该能够在操作之间短暂访问
UI。 - 执行时间应该比通常的同步方法调用快。
就我而言,我对point 1 没有任何疑问,但是对于point 2,它的执行时间似乎与同步方法调用相同。例如见Sample Code 1 和Sample Output 1
示例代码 1:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Before Async Call");
AsyncMethod();
Console.WriteLine("After Async Call");
Console.ReadLine();
}
public async static void AsyncMethod()
{
var firstValue = FirstAsyncMethod("FirstAsyncMethod has been called");
Console.WriteLine("Middle of FirstAsyncMethod and SecondAsyncMethod");
var secondValue = SecondAsyncMethod("SecondAsyncMethod has been called");
Console.WriteLine(await firstValue);
Console.WriteLine(await secondValue);
}
public static async Task<string> FirstAsyncMethod(string value)
{
for (int i = 0; i < 500000000; i++)
{
i = i + 1 - 1;
}
return "Success: "+value;
}
public static async Task<string> SecondAsyncMethod(string value)
{
for (int i = 0; i < 500000000; i++)
{
i = i + 1 - 1;
}
return "Success: " + value;
}
}
示例输出 1:
Before Async Call
Middle of FirstAsyncMethod and SecondAsyncMethod
Success: FirstAsyncMethod has been called
Success: SecondAsyncMethod has been called
After Async Call
但是如果我用Task.Run(()=> )(例如Sample Code 2 和Sample Output 2)调用async 方法,与第一个示例(Sample Code 1)相比,它会减少执行时间。
示例代码 2:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Before Async Call");
AsyncMethod();
Console.WriteLine("After Async Call");
Console.ReadLine();
}
public async static void AsyncMethod()
{
var firstValue =Task.Run(()=> FirstAsyncMethod("FirstAsyncMethod has been called"));
Console.WriteLine("Middle of FirstAsyncMethod and SecondAsyncMethod");
var secondValue = Task.Run(() => SecondAsyncMethod("SecondAsyncMethod has been called"));
Console.WriteLine(await firstValue);
Console.WriteLine(await secondValue);
}
public static async Task<string> FirstAsyncMethod(string value)
{
for (int i = 0; i < 500000000; i++)
{
i = i + 1 - 1;
}
return "Success: "+value;
}
public static async Task<string> SecondAsyncMethod(string value)
{
for (int i = 0; i < 500000000; i++)
{
i = i + 1 - 1;
}
return "Success: " + value;
}
}
示例输出 2:
Before Async Call
Middle of FirstAsyncMethod and SecondAsyncMethod
After Async Call
Success: FirstAsyncMethod has been called
Success: SecondAsyncMethod has been called
我的问题是,为什么第一个示例 (Sample Code 1) 需要像同步方法调用一样的时间?
【问题讨论】:
-
我总是推荐 Eric Lippert 的 Asynchronous Programming in C# 5.0 part two: Whence await? 以消除最严重的误解。 "异步方法的全部意义在于您尽可能多地停留在当前线程上"
-
令人难以置信的是,在 2016 年仍然有人再次问同样的问题。我会说这个问题已经回答了很多次,甚至 MSDN 也有很好的文章解释了 async-await 的工作原理。
-
将异步添加到完全同步的代码不会使其异步...
-
@MatíasFidemraizer 我敢肯定这个问题之前已经被问过(大多数问题都有)。但是,您作为重复指出的那个问题要求对我如何在同一个线程上并行执行操作?进行技术解释,而这个问题询问为什么是异步方法像同步方法那样花时间?。我想说这是两个不同的问题。
-
@MatíasFidemraizer 我已经投票决定重新开放。重复的问题没有解释何时异步执行异步方法的答案。
标签: c# multithreading async-await task