What I need is a class that does async operations in order.
class FooSocket
{
private Socket _Socket;
// Message is a class that wraps a byte array.
public Task<Message> Receive() { /*Bla...*/ };
public Task<int> Send(Message message) { /*Bla...*/ };
}
If I call Send, Receive and Send in this order, I need to send first and queue the remaining receiving and sending operations until the first receiving is finished.
I tried creating a main task field in the class and follow a MainTask = MainTask.ContinueWith(...)
kind of approach. I even wrote a class called Sequencer which does exactly this but it somehow felt wrong, creating nested tasks (using Task.Factory.FromAsync methods) in continuations and stuff.
I also tried to make something like queuing TaskCompletionSource objects and returning their tasks in my Receive/Send methods, checking the queue in an infinite loop on a seperate thread but since I'll have about 200k of FooSocket instances, a thread for each also felt unwise. If I make it a thread-pool, I come to this "a thread-pool shouldn't be used for long-running operations" rule.
I feel close but can't be sure what is the most efficient way to order these jobs.