How to create async thread?

mc 3,681 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.

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,374 questions
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,165 questions
.NET CLI
.NET CLI
A cross-platform toolchain for developing, building, running, and publishing .NET applications.
322 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 56,021 Reputation points
    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 1,911 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