Async-Await 的真正优势? [英] Real advantages of Async-Await?

查看:35
本文介绍了Async-Await 的真正优势?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

之前我已经发布了这个 与在客户端或服务端应用 Async-Await 相关的问题.在继续这个问题之前,请务必阅读该问题,因为它与问题紧密相关.

Earlier i've posted this question related to applying Async-Await at client or at service. Do read the question before going ahead with this question as it is tightly coupled with the question.

根据答案,我测试了 C# 4.0 (TPL) 和 C# 5.0 (Async - Await) 的代码.我正在使用服务提供的方法的异步和同步版本调用服务,并比较每种情况下使用的线程数.以下是我用来测试所用资源的代码:

Based on the answer i've tested the code for C# 4.0 (TPL) and C# 5.0 (Async - Await). I am calling the service using async and sync version of the method provided by the service and comparing the number of threads used in each case. Following is the code i'm using to test the resources used:

主要方法

List<Task<string>> tasksList = new List<Task<string>>();
List<int> asyncThreads = new List<int>();
List<int> tplThreads = new List<int>();
Stopwatch watch = new Stopwatch();
watch.Start();

// Call the Async version of the method
for (int i = 0; i < 500; i++)
{
    tasksList.Add(GetNameFromServiceAsync("Input" + i.ToString(), asyncThreads));
}

Task.WaitAll(tasksList.ToArray());

watch.Stop();

foreach (var item in asyncThreads.Distinct())
{
    Console.WriteLine(item);
}

Console.WriteLine("(C# 5.0)Asynchrony Total Threads = " + asyncThreads.Distinct().Count());
Console.WriteLine(watch.ElapsedMilliseconds.ToString());

watch.Restart();

tasksList.Clear();

// Call the normal method
for (int i = 0; i < 500; i++)
{
    tasksList.Add(GetNameFromService("Input" + i.ToString(), tplThreads));
}

Task.WaitAll(tasksList.ToArray());

watch.Stop();

foreach (var item in tplThreads.Distinct())
{
    Console.WriteLine(item);
}

Console.WriteLine("(C# 4.0)TPL Total Threads" + tplThreads.Distinct().Count());

Console.WriteLine(watch.ElapsedMilliseconds.ToString());

对服务的异步和同步调用

static async Task<string> GetNameFromServiceAsync(string name, List<int> threads)
{
  Console.WriteLine(" Start Current Thread : " + System.Threading.Thread.CurrentThread.ManagedThreadId);
    var task = await client.GetNameAsync(name);
    threads.Add(System.Threading.Thread.CurrentThread.ManagedThreadId);
   // Console.WriteLine("End GetNameFromServiceAsync Current Thread : " + System.Threading.Thread.CurrentThread.ManagedThreadId);
    return task;
}

static Task<string> GetNameFromService(string name, List<int> threads)
{

    var task = Task<string>.Factory.StartNew(() =>
        {
            threads.Add(System.Threading.Thread.CurrentThread.ManagedThreadId);
         //   Console.WriteLine("GetNameFromService Current Thread : " + System.Threading.Thread.CurrentThread.ManagedThreadId);
            return client.GetName(name);
        });

    return task;
}

现在我已经研究了答案并发现了以下结果:

Now I've worked on the answer and find out following results:

  • 如果我对该服务进行 500 次调用,它仅使用 4-5 个线程.
  • TPL 调用产生大约 44-45 个线程.
  • 异步调用的时间约为 17 - 18 秒
  • TPL 调用的时间约为 42 - 45 秒.

我想就我的发现提供一些反馈,以便其他社区成员也能从中受益.这是我之前问题的答案吗?

I want to have some feedback on my findings so that it can be useful to the other community members as well. Is it what the answer of my earlier question??

编辑

问.我的观察得出结论,如果我们使用 Async-Await 而不是 TPL 的 Task.Factory.startNew ,那么它将消耗较少的线程.这有多正确?如果不是,那么提出这种比较的正确方向是什么?

Q. My observation concludes that if we use Async-Await instead of TPL's Task.Factory.startNew , then it will consume lesser threads. HOW CORRECT IS THIS? IF NO, THEN WHAT IS THE RIGHT DIRECTION TO COME UP WITH SUCH COMPARISON?

问.由于我正在学习异步 - 等待,我想通过某种比较和可靠的代码来证明它的价值.

Q. As i am learning async - await, i want to prove its worth by some sort of comparison and solid code.

推荐答案

客户端async(与同步代码相比)通常以轻微的成本内存提高响应能力.

Client-side async (compared to synchronous code) generally improves responsiveness at a slight cost of memory.

服务器端async(与同步代码相比)通常通过减少内存/线程使用来提高可扩展性.这些优势也适用于客户端async(与多线程代码相比).

Server-side async (compared to synchronous code) generally improves scalability by reducing memory/thread usage. These advantages also apply to client-side async (compared to multithreaded code).

这两个都是极端的概括,肯定存在错误的情况.

Both of these are extreme generalizations and there are certainly situations where they're wrong.

更新:

我的观察得出结论,如果我们使用 Async-Await ...,那么它将消耗更少的线程.

My observation concludes that if we use Async-Await ..., then it will consume lesser threads.

async/await 启用可维护的异步代码.它们本身与创建线程没有任何关系.但是,它们通常与 Task.Run(或 Task.Factory.StartNew)一起使用来创建后台任务.

async / await enable maintainable asynchronous code. By themselves, they don't have anything to do with creating threads. However, they are often used with Task.Run (or Task.Factory.StartNew) to create background tasks.

因为我正在学习异步 - 等待,我想通过某种比较和可靠的代码来证明它的价值.

As i am learning async - await, i want to prove its worth by some sort of comparison and solid code.

asyncawait 是编译器转换.它们使编写异步程序变得更容易——仅此而已.

async and await are compiler transformations. They make it easier to write asynchronous programs - that is all.

如果您将它们与同步代码进行比较,那么您通常会看到改进的响应能力和/或可扩展性.如果您将它们与现有的异步代码进行比较,那么它们通常会稍微降低效率,但在代码可维护性方面足以弥补这一点.

If you compare them to synchronous code, then you'll usually see improved responsiveness and/or scalability. If you compare them to existing asynchronous code, then they'll usually be slightly less efficient but more than make up for that in terms of code maintainability.

这篇关于Async-Await 的真正优势?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆