Untill now, i used IOCP for tcp servers which was pretty easy and comfortable, but this time i want to use the Async / Await tech. that was released in C# 5.0.
I think you need to get your terminology right.
Having BeginOperation
and EndOperation
methods is called Asynchronous Programming Model (APM). Having a single Task
(or Task<T>
) returning method is called Task-based Asynchronous Pattern (TAP). I/O Completion Ports (IOCP) are a way to handle asynchronous operations on Windows and asynchronous I/O methods using both APM and TAP use them.
What this means is that the performance of APM and TAP is going to be very similar. The big difference between the two is that code using TAP and async
-await
is much more readable than code using APM and callbacks.
So, if you want to (or have to) write your code asynchronously, use TAP and async
-await
, if you can. But if you don't have a good reason to do that, just write your code synchronously.
On the server, a good reason to use asynchrony is scalability: asynchronous code can handle many more requests at the same time, because it tends to use fewer threads. If you don't care about scalability (for example because you're not going to have many users at the same time), then asynchrony doesn't make much sense.
Also, your code contains some practices that you should avoid:
- Don't use
async void
methods, there is no good way to tell when they complete and they have bad exception handling. The exception is event handlers, but that applies mostly to GUI applications. - Don't use
Task.Run()
if you don't have to.Task.Run()
can be useful if you want to leave the current thread (usually the UI thread) or if you want to execute synchronous code in parallel. But it doesn't make much sense to use it to start asynchronous operations in server applications. - Don't ignore
Task
s returned from methods, unless you're sure they're not going to throw an exception. Exceptions from ignoredTask
s won't do anything, which could very easily mask a bug.