简体   繁体   中英

Sharing Socket instance between threads

I have a multi-threaded application, where different components (running in different threads) needs to send out UDP messages. For now they all share the same Socket instance.

The socket is created as Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp) and socket.Send(byte[] message) is called from the threads. Socket.Send is the only method that is called.

Is this a bad approach? I haven't seen any problems yet, but I fear that this is not the way sockets were intended to be used.

the most "correct" solution is to create a method that calls the socket.send method and protect this call by using a lock or mutex. This way wikl garantee that socket object is used for once thread at a given time. You can also archieve this by using a queue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM