I'm using TaskCompletionSource
in my software to distribute network packets to async
/await
methods. So in my code, there are various points where the software needs to wait for a network packet getting demultiplexed from the receive handler and handed over to a method async Wait()
. There can be many, many packets per second and I'm deciding if I want to push the packet to TaskCompletionSource
or put it into a Queue
. So, whenever theres no TaskCompletionSource
I will create a new one, which leads to a new Task
object.
According to this question Do I need to dispose of a Task? and according to this blog Parallel Programming with .NET Task
s don't need be Dispose
d. However, I'm sometimes instantiating many thousand TaskCompletionSource
per second. The detailed answer in the linked blog also says, that Task
may use internally WaitHandle
. Now I have the strong feeling that my case is the exact case, where I should use Dispose
on the tasks from the TaskCompletionSource
.
This is how I wait for a new packet. This method will be calles with await
and can also be called heavily in parallel:
public async Task<Packet> Wait()
{
Packet packet;
lock (sync)
if (packets.TryDequeue(out packet))
return packet;
else
waiter = new TaskCompletionSource<Packet>();
return await waiter.Task;
}
My method of pushing packets from the network handler looks like this:
public void Poke(Packet packet)
{
lock (sync)
if (waiter == null)
packets.Enqueue(packet);
else
waiter.SetResult(packet);
}
I'm on .NET Core >= 2.2. The blog entry states that the behavior of WaitHandle
also changed in .NET 4.5.
Question: Do I need to Dispose Task
s in this specific scenario? Will I create many Handles
, if I don't Dispose
the Tasks created by TaskCompletionSource
when receiving many packets coming along this code path? Is this the scenario the blog entry warned me about?
Please refrain from telling me, that this method is a bad choice as long as you can't tell me a better method being very compatible to async
/await
pattern and also being able to distribute those packets to various selected listeners. Please also don't tell me, that creating many objects because of many network packets is generally a bad idea.