Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In
Continue with Google
Continue with Facebook
or use


Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here
Continue with Google
Continue with Facebook
or use


Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.


Have an account? Sign In Now

Sorry, you do not have a permission to ask a question, You must login to ask question.

Continue with Google
Continue with Facebook
or use


Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Stack Ask

Stack Ask Logo Stack Ask Logo

Stack Ask Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 3461
Next
Answered
Nam Nguyen
  • 0
Nam NguyenBeginner
Asked: December 4, 20212021-12-04T10:22:39+00:00 2021-12-04T10:22:39+00:00In: .Netcore

Giống và khác nhau giữa async await và multi thread trong c#

  • 0

Mọi người cho em hỏi sự giống và khác nhau giữa async await và multi thread trong C# với ạ?

Khi nào thì mình nên dùng async await, khi nào thì mình nên dùng multi thread ạ?

Em cảm ơn ạ.

asyncawaitc#multithread
  • 3 3 Answers
  • 262 Views
  • 0 Followers
  • 0
Answer
Share
  • Facebook
  • Report

3 Answers

  • Voted
  • Oldest
  • Recent
  1. Best Answer
    tvd12 Enlightened
    2021-12-04T14:34:16+00:00Added an answer on December 4, 2021 at 2:34 pm
    This answer was edited.

    Hãy nhìn vào chương trình này nhé:

    class Program
    {
        public static void Main(string[] args)
        {
            Thread.CurrentThread.Name = "main";
            Console.WriteLine("Start Thread: " + Thread.CurrentThread.Name);
            Hello().GetAwaiter().GetResult();
            Console.WriteLine("End Thread: " + Thread.CurrentThread.Name);
            Thread.Sleep(100);
        }
    
        public static async Task Hello()
        {
            Console.WriteLine("Current Thread at Start Hello: " + Thread.CurrentThread.Name);
            await Task.Run(() =>
            {
                Thread.CurrentThread.Name = "task";
                Console.WriteLine("Current Thread at Task: " + Thread.CurrentThread.Name);
                Console.WriteLine("Hello World");
            });
            Thread.CurrentThread.Name = "async";
            Console.WriteLine("Current Thread at End Hello: " + Thread.CurrentThread.Name);
        }
    }
    

    Và kết quả nó sẽ thế này:

    Start Thread: main
    Current Thread at Start Hello: main
    Current Thread at Task: task
    Hello World
    Current Thread at End Hello: async
    End Thread: main
    

    Như vậy có nghĩa là việc async await đang diễn ra trên các thread khác nhau, vậy nên theo quan điểm của anh thì trong C# async / await chẳng quan chỉ là 1 cách viết đơn giản hơn cho lập trình multi thread mà thôi.

    Em có thể tham khảo source code của lớp Task sẽ thấy là nó đang sử dụng kết hợp giữa thread pool và task queue.

    Đọc source code lớp threadpool anh đang thấy khởi tạo mặc định ban đầu max 32 thread:

    private const int INITIAL_SIZE = 32;
    internal volatile IThreadPoolWorkItem[] m_array = new IThreadPoolWorkItem[INITIAL_SIZE];
    private volatile int m_mask = INITIAL_SIZE - 1;
    
    • 1
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report
  2. Nguyễn Thái Sơn Professional
    2021-12-04T12:27:49+00:00Added an answer on December 4, 2021 at 12:27 pm

    đầu tiên e hiểu bất đồng bộ là gì

    • 0
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report
    • Nam Nguyen Beginner
      2021-12-04T12:33:17+00:00Replied to answer on December 4, 2021 at 12:33 pm

      Là xử lý các tác vụ cùng lúc đúng không ạ?

      • 0
      • Share
        Share
        • Share on Facebook
        • Share on Twitter
        • Share on LinkedIn
        • Share on WhatsApp
        • Report

You must login to add an answer.

Continue with Google
Continue with Facebook
or use


Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 581
  • Answers 1k
  • Best Answers 63
  • Users 299
  • Popular
  • Answers
  • monkey

    [Deep Learning] Làm thế nào để xác định được cái ...

    • 16 Answers
  • Tú Trần Anh

    [Ezyfox Server] Unity game client không gửi được command khi ...

    • 12 Answers
  • monkey

    [Go] khi nào go func được gọi?

    • 10 Answers
  • Nguyễn Thái Sơn
    Nguyễn Thái Sơn added an answer em cảm ơn, vậy mỗi câu truy vấn luôn có… June 24, 2022 at 4:31 pm
  • tvd12
    tvd12 added an answer Việc chuyển này cũng có nhiều khó khăn là nó… June 24, 2022 at 3:08 pm
  • tvd12
    tvd12 added an answer 1. Vì socket là giữ kết nối nên em sẽ… June 24, 2022 at 3:02 pm

Related Questions

  • Thưởng Đặng Văn

    Multiple tenant multiple database .net core

    • 10 Answers
  • LarreyK

    Làm sao để chia room và giới hạn số lượng ...

    • 5 Answers
  • Nguyen Nam

    Lấy giá trị của TextBox trước và sau sự kiện ...

    • 2 Answers

Top Members

tvd12

tvd12

  • 65 Questions
  • 1k Points
Enlightened
monkey

monkey

  • 91 Questions
  • 620 Points
Enlightened
Nguyễn Thái Sơn

Nguyễn Thái Sơn

  • 148 Questions
  • 229 Points
Professional

Trending Tags

.net core abstract class analytics android ansible anti-flooding apache poi api async asyncawait atomicboolean backend backend nestjs bash script batch bean big project binding bitcoin blockchain blog boot-nodes branch british buffered build bundle c# cache caching callback career career path cast centos chat cloud cloud reliability commit company content-disposition contract cors cosmos css database datasource datastructure decentralized exchange deep learning design-pattern devops dex distraction programing docker download draw.io du học dữ liệu lớn eclip editor employee english erc20 erc721 eth ethereum ethereum login extensions exyfox ezyfox ezyfox-boot ezyfox-server ezyfoxserver ezyhttp facebook fe flutter freetank french front-end frontend fullstack fulltextsearch future game game-box game-room game-server get git go golang google grapql grpc guide hazelcast hibernate hibernateconfig html http https index indexing integration-test intellij interface interview io ipfs isolate issue it java javacore java core javascript java spring javaw java web job jpa js json jsp & servlet jvm jwt kafka keep promise kerberos keycloak kotlin language languague library load-balancing log log4j log4j-core login lưu trữ machine learning macos math maven merge messaging metamask microservice model mongo msgpack multiple tenant multithread multithreading mysql n naming naming convention netcore netty nft nft game nio nodejs non-blocking io opensource optimize orm pagination pancakeswap panic pgpool phỏng vấn pointer postgresql pre programming promise push message android python python unicode question queue rabbitmq reactive reactjs reactjs download recyclerview redis request resource rest roadmap ropssten ropsten rust rxjava schedule search security server shift jis singleton sjis slack smart contract socket soft delete sosanh spring spring-boot-test spring-jpa spring aop spring boot springboot spring data jpa spring redis spring security springsecurity springwebflux mysql sql sql server sse stackask storage stream structure trong spring boot system environment variables thread threadjava thymeleaf totp tracking location unit test unity upload file vector view volatile vue vue cli web3 web3 client webpack websocket windows 11 winforms work zookeeper

Footer

Stack Ask

Stack Ask is where Developers Ask & Answers. It will help you resolve any questions and connect you with other people.

About Us

  • Meet The Team
  • About Us
  • Contact Us

Legal Stuff

  • Terms of Service
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2021 Stack Ask. All Rights Reserved
Powered by youngmonkeys.org