Radsta
Radsta

Reputation: 28

Is waiting inside a callback safe in C#?

I have a BeginRead that calls a ReadCallback function upon completion. What I want to do in the callback is wait for a ManualResetEvent on a buffer to tell me if the buffer is empty or not, so I can issue a new BeginRead if I need more data. I have implemented this and it works. But my question is : is it safe to wait inside a callback? I'm new to C#, if these were regular threads I wouldn't have doubts, but I'm not sure how C# treats callbacks.

Thank you.

Upvotes: 1

Views: 117

Answers (1)

usr
usr

Reputation: 171206

APM callbacks are called on the thread-pool in all cases that I can think of.

That reduces your question to "Can I block thread-pool threads?". The answer to that is generally yes but it has downsides.

It is "safe" to do so until you exhaust the pool (then you risk deadlocks and extreme throughput reduction like >1000x).

The other downsides are the usual downsides of blocking threads in general. They cost a lot of memory to keep around. Lots of threads can cause lots of context switches.

Can't you just use await? I imagine your code to look like this:

while (true) {
 var readResult = await ReadAsync(...);
 await WaitForSomeConditionAsync(); //Instead of ManualResetEvent.
}

No blocking. Very simple code. There is no need to do anything special to issue the next read. It just happens as part of the loop.

My working model is something similar to producer/consumer.

Sounds like a good use for TPL Dataflow. Dataflow automates the forwarding of data, the waiting and throttling. It supports async to the fullest.

Upvotes: 3

Related Questions