0

I wanna ask you if is semantically correct that a gui WRITE on a socket? it could be a problem? There is the risk of block in the GUI ??

Thanks in advance

Audette
  • 47
  • 6
  • 1
    In general, any long-running or potentially blocking operation should take place on a background thread, to maintain a responsive GUI. A socket write *can* block, if internal transmit buffers are full. – Jonathon Reinhart Oct 18 '14 at 17:28

1 Answers1

1

It depends on how you've configured the socket. A non-blocking socket will not, of course, block your GUI thread. But IMHO they are considerably harder to write code around, due to the requirement to handle the non-fatal failure to send when you try to.

IMHO a much better model is to take advantage of one of the asynchronous paradigms sockets offer. Unfortunately, the System.Net.Sockets.Socket class hasn't been updated to fit with the new async/await features in C#. But it still has two very usable asynchronous models to choose from (either the original "Begin/EndXXX" model, or the 'XXXAsync" model, which in spite of its name doesn't work directly with async/await).

If you are willing to go to a slightly higher-level API with TcpListener, TcpClient and streams, then you can use async/await and this may provide you with an easier way to write the code. I found this earlier SO discussion in which someone's posted a short sample showing how that could be done: Using .Net 4.5 Async Feature for Socket Programming

Community
  • 1
  • 1
Peter Duniho
  • 68,759
  • 7
  • 102
  • 136
  • Doing a thread safe blocking queue between Gui Thread and Sender thread is also a good solution? – Audette Oct 20 '14 at 08:40
  • I would not dedicate a thread to I/O at all. .NET already does this for you, with a dedicated IOCP thread pool, which you get to use "for free" when you use the asynchronous APIs for Socket (and I assume for socket-based higher-level classes like TcpListener/Client, but I don't know off the top of my head). So, no...I guess I wouldn't agree that a "thread safe blocking queue between GUI and Sender thread" is a good solution. – Peter Duniho Oct 20 '14 at 08:44
  • ok i have read different topic about this paradigms. But unfortunately i haven't solve my problem .. i will explain it better... I'm realaizing an remote control application in c#. I have a server application that can receive 1 connection at time-> so it don't need asynchronously features. While my client application receive events like ( key down) and have to transmit it to server application. The problem is that i dont'want that it write also on a socket cause it can block the gui... Can i solve it with this paradigms? – Audette Oct 20 '14 at 12:37
  • Yes, of course. The approaches I've suggested solve the "don't block the GUI by writing to a socket" problem _specifically_. Just because you aren't dealing with multiple connections, that doesn't mean that asynchronous techniques aren't useful. – Peter Duniho Oct 20 '14 at 17:11