❔ Can I Fire and forget ALOT of tasks? If so how do i do this efficiently?
I have a websocket connection, the server will always only have one task that reads from it, but after it has read the message and passed it onto the message handler i want it to begin reading the next message and forget the task it just started...
This might result in alot of tasks being started, how do i do this in a efficient manner, or should i not do this at all?
9 Replies
Example class
Just fire the task and discard result?
_ = Task.Run(() => HandleMessageAsync(body.Value, cancellationToken));
well yeah thats the easy way but i dont think thats smart
memory usage n stuff
Why do you think so?
CLR has garbage collection
im aware
but this means allocating thousands of tasks that way
the same way you would use ArrayPool<> instead of allocating arrays all the time, im asking this question because doing this at such a frequency might be bad
If you're worried about memory, then .NET will realloc as needed (when tasks finish executing). If you're worried about processing power, the thread pool thread takes care of that. It enqueues busy tasks as needed.
That means when you're creating thousands of tasks in a short timespan, not all of them will be actively working
garbage collection isnt free
(this also doesnt mean you should also micro optimize everything)
anyway
will fire and forget
but keep in mind your method will run sync-ly until the first await
in addition to what Cyberres said, there is also
ValueTask
/ValueTask<T>
which are structs so u dont add additional work for the GC
which can come in quite handy for fire and forget.
ofc dont blindly use it but check out if it fits ur use cases
https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.valuetask-1?view=net-7.0
https://devblogs.microsoft.com/dotnet/understanding-the-whys-whats-and-whens-of-valuetask/Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.