Is Async/Await using Task.Run starting a new thread asynchronously?

后端 未结 3 1483
耶瑟儿~
耶瑟儿~ 2020-12-02 15:41

I have read a lot of articles and still cant get understand this part.

Consider this code :

    private async void button1_Click(object sender, Event         


        
相关标签:
3条回答
  • 2020-12-02 16:07

    1

    There's a big difference if you don't await the Task or you await it:

    • Case you don't await it: DoSomething is called but next sentence is executed while DoSomething Task hasn't been completed.

    • Case you await it: DoSomething is called and next sentence is executed once DoSomething Task has been completed.

    So, the need of async/await will depend on how you want to call DoSomething: if you don't await it is like calling it the fire & forget way.

    2

    Is it running on the main UI but on a separate thread or is it running on a seperate thread and separate is asynchronously inside that method?

    Asynchronous code sometimes means other thread (see this Q&A Asynchronous vs Multithreading - Is there a difference?). That is, either if the code is being executed in a separate thread from the UI one or it lets continue the processing of the UI thread while it gets resumed, it's nice because UI loop can still update the screen while other tasks are being done in parallel without freezing the UI.

    An asynchronous method (i.e. async method) is a syntactic sugar to tell the compiler that await statements should be treated as a state machine. The C# compiler turns your async/await code into a state machine where code awaiting a Task result is executed after the code that's being awaited.

    Interesting Q&As

    You might want to review these other Q&As:

    • Async/Await vs Threads
    • What's the difference between Task.Start/Wait and Async/Await?
    • async/await - when to return a Task vs void?
    • Is Async await keyword equivalent to a ContinueWith lambda?

    OP said...

    [...] But does this mean that "async/await" will fire off a thread and Task.Run also fires off a thread or are they both the same thread?

    Using async-await doesn't mean "I create a thread". It's just a syntactic sugar to implement continuations in an elegant way. A Task may or may not be a thread. For example, Task.FromResult(true) creates a fake task to be able to implement an async method without requirement it to create a thread:

    public Task<bool> SomeAsync()
    {
        // This way, this method either decides if its code is asynchronous or 
        // synchronous, but the caller can await it anyway!
        return Task.FromResult(true);
    }
    
    0 讨论(0)
  • 2020-12-02 16:07

    The type Task<TResult> requires you to return a TResult from your task. If you don't have anything to return, you can use Task instead (which, incidentally, is the base class of Task<TResult>).

    But keep in mind that a task is not a thread. A task is a job to be done, while a thread is a worker. As your program runs, jobs and workers become available and unavailable. Behind the scenes, the library will assign your jobs to available workers and, because creating new workers is a costly operation, it will typically prefer to reuse the existing ones, through a thread pool.

    0 讨论(0)
  • 2020-12-02 16:13
    1. The purpose of creating Async methods is so you can Await them later. Kind of like "I'm going to put this water on to boil, finish prepping the rest of my soup ingredients, and then come back to the pot and wait for the water to finish boiling so I can make dinner." You start the water boiling, which it does asynchronously while you do other things, but eventually you have to stop and wait for it. If what you want is to "fire-and-forget" then Async and Await are not necessary.

    Simplest way to do a fire and forget method in C#?

    1. Starting a new task queues that task for execution on a threadpool thread. Threads execute in the context of the process (eg. the executable that runs your application). If this is a web application running under IIS, then that thread is created in the context of the IIS worker process. That thread executes separately from the main execution thread, so it goes off and does its thing regardless of what your main execution thread is doing, and at the same time, your main execution thread moves on with its own work.
    0 讨论(0)
提交回复
热议问题