Should writes to NetworkStream be performed asynchronously
Given that NetworkStream.Write()
is a blocking call should a method like SendMessage()
create a new thread to perform the write operation or should the SendMessage()
method block until the message is sent or an exception occurs?
My gut tells me it is reasonable to block this method but looking at a re开发者_JAVA技巧ally nice example of sockets in C# I am finding they are creating a new thread. The main issue I see with creating another thread is error handling.
PS: I am aware of the Async versions of Write, Read and so forth but find IAsyncResult rather confusing and am currently holding off on using those options.
If you are calling SendMessage()
on a UI thread then it will block it and your application will "freeze". Instead of creating a new thread each time you want to send data, use ThreadPool.QueueUserItem(o => SendMessage())
or Task.Factory.StartNew(() => SendMessage())
from Task Parallel Library in .NET 4.0
If your application is servicing clients and you create a new thread for each client, then SendMessage()
can block if you don't want to do other work while sending the data to the client.
Creating a new thread for each client has one drawback: lots of threads will consume a lot of resources and most of the time these threads will be idling while they could be servicing other clients in the meantime. If you wish to create a high performance server application you should learn about asynchronous programming.
Check out Async CTP. It will let you write asynchronous code that looks like synchronous code without messy callbacks
public async void SendMessage()
{
try {
await socket.WriteAsync(buffer, 0, buffer.Length);
} catch (...) {
// handle it
}
}
Now SendMessage() won't block because it will be executed asynchronously and it does not look scary at all!
I strongly recommend you to take a look at the Task Parallel Library.
You can create Task from any async pattern in current .net.
Task will be executed on the thread pool, and exceptions will be marshaled kindly from other threads.
精彩评论