gpt4 book ai didi

c# - 在 C# 中异步总是异步的吗?

转载 作者:太空宇宙 更新时间:2023-11-03 23:19:33 25 4
gpt4 key购买 nike

<分区>

我正在为我的项目进行 asyncawait 的研发。我所了解到的是,当 async 方法被调用时,它会释放线程并让线程被其他人使用。我们可以使用 await 关键字为 await-able 方法设置回调,当结果准备好时该方法返回值。如果发生这种情况:

  1. 我们应该能够在操作之间短暂访问UI
  2. 执行时间应该比通常的同步方法调用更快。

在我的例子中,我对point 1没有疑问,但是对于point 2,它的执行时间似乎与同步方法调用相同。例如,请参阅 示例代码 1示例输出 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(()=> ) 调用 async 方法(例如 示例代码 2示例输出 2),与第一个示例(示例代码 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

我的问题是,为什么第一个示例(示例代码 1)像同步方法调用一样耗时?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com