Based on your question, you need an agent to process multiple process to send and receive messages in parallel, but processing these messages has to have asynchronous behavior, because you are dealing with I/O. Most I/O operations (including TCP socket) is usually blocking, therefore having async implemented is the best option.
But combining parallel with async operation is not an easy task if you use .NET EAP (event asynchronous pattern), that you have shown in your question. I know the .NET EAP model, because you are using Beginxxx and Endxxx pattern in the method. This in turn makes async-await usage more difficult. It is difficult, because then all of the async and await operations must encapsulate the Beginxxx and Receivexx (or Endxxx) method pair.
You should be aware that the EAP model is now considered legacy async model in .NET 4.5 and above, just check on the MSDN Library links below.
For parallel programming, it is available in NET TPL (Task Parallel Library) model. This .NET TPL only describes parallel programming. If you are going to use async-await, you need to check the .NET TAP (Task Asynchrony Pattern) model, and this is why .NET TAP is not exactly the same as .NET TPL.
I suggest you to use the existing .NET 4.5 (and above) Socket API in
System.Net.Sockets (for example, just look at the
TcpListener's methods that has Async suffix) instead, and then combine each execution of the async method in a parallel execution.
Second, don't use a single context for your bot. Having parallel programming means you should be aware that you are going to have multiple execution contexts running separately. Having just one context is then will increase difficulties, because you should manage states for different message conversations. But your mileage may vary, though.
Last suggestions: there's no single bullet for any concurrency model.
For more information about .NET EAP, please visit: https://msdn.microsoft.com/en-us/library/ms228969(v=vs.110).aspx
For more information about .NET TAP, please visit:
For more information about .NET TPL, please visit:
UPDATE 1 (based on the comments):
Task scheduler? Yes, for task scheduler/sync context in TPL, please visit sample of
TaskScheduler in the .NET TPL:
But be careful when using this class, please ensure that you have added
CancellationToken support in all of your Task creation, otherwise you'll get unpredictable behavior if your process is locked/timed out.
If you want to have more control on how you want the sequencing and granularity of the max number of parallel operations, you can then combine parallel programming in .NET TPL using your customized parallel execution. For example, you can run the Parallel.For with the additional
For example: see the documentation of
ParallelOptions usage at: