davidfowl / AspNetCoreDiagnosticScenarios

This repository has examples of broken patterns in ASP.NET Core applications
7.69k stars 740 forks source link

Async code inside a long running background thread #48

Open guylando opened 5 years ago

guylando commented 5 years ago

Arrived to this great repository after watching your great talk on scalability on youtube.

The situation here: https://github.com/davidfowl/AspNetCoreDiagnosticScenarios/blob/master/AsyncGuidance.md#avoid-using-taskrun-for-long-running-work-that-blocks-the-thread is relevant for us (we have ~10 such workers which keep synchronizing some database tables, each worker for a different table, into memory cache so that when http requests come we can handle them quickly using the data from the memory cache instead of querying the database) however we run some async calls which don't have alternative sync calls from that background worker and the example shown is sync so it is unclear how to correctly start async code in that new background thread without going back to using .Wait or .Result?

Maybe in such cases we need to use Task.Factory.StartNew with TaskCreationOptions.LongRunning which allows to smoothly run async task? and if so can you please provide an example of how to correctly do it because I saw that you wrote that its error prone if to pass wrong parameters

Thanks!

davidfowl commented 5 years ago

It's fine to use do background async work the trick is to understand that if you do async work, you're not blocking a running thread. The thread pool is very likely still being used to use resume the async operation. As long as you're ok with that then keep on doing what you're doing (without using .Result of course).

What does your code look like today?

guylando commented 5 years ago

Today our Startup.cs Configure methods start "and forget" about 10 tasks using:

_ = StaticClass.MethodLoadingTableAIntoMemoryCache(...);
_ = StaticClass.MethodLoadingTableBIntoMemoryCache(...);
_ = StaticClass.MethodLoadingTableBIntoMemoryCache(...);

where MethodLoadingTableAIntoMemoryCache, MethodLoadingTableBIntoMemoryCache,.. methods are async.

vlm--- commented 5 years ago

You should definately read great 3-part series from Andrew Lock about how you can run async code on startup: https://andrewlock.net/running-async-tasks-on-app-startup-in-asp-net-core-part-1

DomenPigeon commented 1 year ago

Hi, @davidfowl I have seen this code, where you suggest spawning a new thread manually and rembemered this from Concurrency in C# Cookbook from Stephen Cleary.

Is this one of those exceptions :) ?

image image