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
  • 289 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 629
  • Answers 1k
  • Best Answers 70
  • Users 322
  • 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
  • Tú Trần Anh

    Lỗi LNK khi sử dụng EzyFox Server C++ client sdk

    • 11 Answers
  • tvd12
    tvd12 added an answer Qua rất nhiều trình gửi mail và các dự án… August 12, 2022 at 3:15 pm
  • monkey
    monkey added an answer use cosmwasm_std::{ Response, StdError, StdResult, Addr, Storage }; use cw_storage_plus::Map;… August 11, 2022 at 4:33 am
  • monkey
    monkey added an answer # Set up biến môi trường: source <(curl --insecure https://raw.githubusercontent.com/CosmWasm/testnets/master/malaga-420/defaults.env)… August 10, 2022 at 9:31 am

Related Questions

  • Thưởng Đặng Văn

    Multiple tenant multiple database .net core

    • 11 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

  • 70 Questions
  • 1k Points
Enlightened
monkey

monkey

  • 101 Questions
  • 709 Points
Enlightened
Nguyễn Thái Sơn

Nguyễn Thái Sơn

  • 153 Questions
  • 234 Points
Professional

Trending Tags

.net core abstract class ai analytics android ansible anti-flooding apache poi api artificial intelligence async asyncawait atomicboolean backend backend nestjs bash script batch bean big project binding bitcoin blockchain blog boot-nodes branch british btree buffered build bundle c# cache caching callback career career path cast centos chat cloud cloud reliability commit company content-disposition contract cors cosmos cosmos-sdk css database datasource datastructure decentralized exchange deep learning deploy contract design-pattern devops dex distraction programing dns docker download draw.io du học duration dữ liệu lớn eclip editor employee english erc20 erc721 eth ethereum ethereum login extensions exyfox ezyfox ezyfox-boot ezyfox-server ezyfoxserver ezyhttp ezymq-kafka ezyredis facebook fe floating point flutter freetank french front-end frontend fullstack fulltextsearch future game game-box game-room game-server gateway get git glide 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 private_key programming promise push message android push notification python python unicode question queue rabbitmq reactive reactjs reactjs download recyclerview redis request resource rest roadmap ropssten ropsten rr rust rxjava s3 schedule search security server shift jis singleton sjis slack smart contract soap socket socket server soft delete sosanh spring spring-boot-test spring-jpa spring aop spring boot springboot spring data jpa spring redis springsecurity spring security springwebflux mysql sql sql server sse stackask storage stream structure trong spring boot system environment variables thread threadjava thymeleaf totp tracking location transfer transfer git uniswap unit test unity upload file validate vector view volatile vue vue cli web 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