How to create async thread?

mc 5,426 Reputation points
2022-12-17T11:34:42.237+00:00
public async Task Update()  
{  
//code.  
}  

how to run it in thread?

I can not use like this: var thread =new Thread(Update); it must be void.

Developer technologies ASP.NET ASP.NET Core
Developer technologies .NET Other
Developer technologies .NET .NET CLI
{count} votes

2 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 77,686 Reputation points Volunteer Moderator
    2022-12-17T23:42:56.533+00:00

    Your issue is that its an awaitable task, not that its void

    var task = Task.Run(() => Update());   
    await task;   
    

    or simply:

    await Task.Run(() => Update());   
       
    

  2. SurferOnWww 4,631 Reputation points
    2022-12-18T00:50:58.117+00:00

    Please read the following documents:

    Async Programming : Introduction to Async/Await on ASP.NET
    https://learn.microsoft.com/en-us/archive/msdn-magazine/2014/october/async-programming-introduction-to-async-await-on-asp-net

    "Async and await on ASP.NET are all about I/O. They really excel at reading and writing files, database records, and REST APIs. However, they’re not good for CPU-bound tasks. You can kick off some background work by awaiting Task.Run, but there’s no point in doing so. In fact, that will actually hurt your scalability by interfering with the ASP.NET thread pool heuristics. If you have CPU-bound work to do on ASP.NET, your best bet is to just execute it directly on the request thread. As a general rule, don’t queue work to the thread pool on ASP.NET."

    Avoid blocking calls
    https://learn.microsoft.com/en-us/aspnet/core/performance/performance-best-practices?view=aspnetcore-6.0#avoid-blocking-calls

    "Do not: Call Task.Run and immediately await it. ASP.NET Core already runs app code on normal Thread Pool threads, so calling Task.Run only results in extra unnecessary Thread Pool scheduling. Even if the scheduled code would block a thread, Task.Run does not prevent that."

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.