0

I have put Microsofts code <here> into a separate .cs file and call it from Form1 using the button below

private async void Button2_Click(object sender, EventArgs e)
{
    Server.StartListening();
}

What would be the correct way to start the socket listener without the whole UI freezing

I Hate Java
  • 27
  • 1
  • 6
  • The example code you link to is designed to be run from a console, and it has an infinite while loop with no way to break out of it other than an error condition. So that's why your UI is freezing. – Erik Funkenbusch Apr 11 '17 at 15:06
  • That's an *old* sample. It doesn't take advantage of tasks awaiting. Unfortunately, the Socket class doesn't have any methods that return Task. You have to use `TaskFactory.FromAsync` to convert Begin/End calls to tasks, as [shown in this question](http://stackoverflow.com/questions/17093206/high-performance-asynchronous-awaiting-sockets). The example becomes a lot simpler then – Panagiotis Kanavos Apr 11 '17 at 15:10
  • Why don't you use TcpListener instead of a socket? It provides task-based methods like [AcceptSocketAsync](https://msdn.microsoft.com/en-us/library/system.net.sockets.tcplistener.acceptsocketasync(v=vs.110).aspx) and [AcceptTcpClientAsync](https://msdn.microsoft.com/en-us/library/system.net.sockets.tcplistener.accepttcpclientasync(v=vs.110).aspx) – Panagiotis Kanavos Apr 11 '17 at 15:14
  • You can use BeginAccept : https://msdn.microsoft.com/en-us/library/system.net.sockets.socket(v=vs.110).aspx – jdweng Apr 11 '17 at 15:34
  • Thanks everyone, I'll look into it. I'm just trying to make a client than can send a file to a different client – I Hate Java Apr 11 '17 at 16:21

1 Answers1

0

Check out Task.Run(). Only using async won't make the whole method/event asynchronous. The example is not using a UI.

Fredrik Karlsson
  • 113
  • 1
  • 1
  • 9