Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET C# Socket Concurrency issues

An instance of System.Net.Sockets.Socket

can be shared by 2 threads so one use the send() method and another it's receive() method ?

Is it safe?

Well, I need it to be not only thread-safe, but also that the send/receive methods be non-syncronized, so as to let each thread call them concurrently.

Do I have another way of doing it ?

Thanks for helping, I am experienced in java but having a hard time trying to make this one.

like image 206
David Hofmann Avatar asked Aug 26 '09 19:08

David Hofmann


3 Answers

It should be safe, yes. The Socket class is quoted by MSDN to be fully thread-safe.

I don't know if it's a good idea however. You might be making it difficult for yourself by using two threads. You probably want to look at BeginSend and BeginReceive for asynchronous versions, in which case you shouldn't need multiple threads.

like image 191
Thorarin Avatar answered Nov 20 '22 07:11

Thorarin


Little off topic, but using de sync methods is only usefull if you have limited clients. I figured out that async sockets are slower with response. The async soockets are much better with handling many clients.

So: sync is way faster. async is more scalable

like image 2
Jeroen Avatar answered Nov 20 '22 08:11

Jeroen


Yes, it is perfectly safe to access send and recieve from two different threads at the same time.

If you want your application to scale to 100's of active sockets then you'll want to use the BeginReceiveve/BeginSend methods as opposed to creating threads manually. This will do magic behind the scenes so that you don't spawn 100's of threads to process the sockets. What exactly it does is platform dependent. On windows you'll use the 'high performance' io completion ports. Under linux (mono) you'll use epoll I believe. Either way, you'll end up using a lot less threads than active sockets, which is always a good thing :)

like image 1
Alan Avatar answered Nov 20 '22 08:11

Alan