Question: I am trying to Stop Server at form close but its not working. It Throws exception at

clientSocket = serverSocket.AcceptTcpClient();

> 
> Exception : A blocking operation was interrupted by a call to WSACancelBlockingCall
> 
> 
> 

I tried to Stop Server at different places but its not working

```
 private void Form1_Load(object sender, EventArgs e)
    {
        serverSocket = new TcpListener(9361);
        clientSocket = default(TcpClient);
        Thread listen = new Thread(listenClients);
        listen.Start();

    }

    protected override void OnFormClosing(FormClosingEventArgs e)
    {
        base.OnFormClosing(e);
        serverSocket.Stop();
    }

    public void listenClients()
    {

        serverSocket.Start();
        while ((true))
        {

            clientSocket = serverSocket.AcceptTcpClient();

            Thread listen = new Thread(readClient);
            listen.Start();

        }
    }

    public void broadcast(Image img)
    {
        CamView.Image = img; 
    }  //en

    private void readClient()
    {
        while ((true))
        {
            try
            {

                NetworkStream networkStream = clientSocket.GetStream();
                networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);

                    using (MemoryStream ms = new MemoryStream(bytesFrom))
                    {
                        Image mss = Image.FromStream(ms);
                        broadcast(mss);
                    }
            }
            catch 
            {

            }
        } //end while
    } //end readClint

```

Answer: 
This exception is perfectly valid in your case - `serverSocket.AcceptTcpClient()` is a blocking operation that either returns a `TcpClient` instance or throws a `SocketException`. 

Here is how you can solve this problem without changing the architecture of the application:

```
try
{
    serverSocket = serverSocket.AcceptTcpClient();
}
catch(SocketException e)
{
    if (e.SocketErrorCode != SocketError.Interrupted)
        throw;
    else
        break;
}

```
please keep Try catch block inside following code.

```
serverSocket = new TcpListener(9361);
    clientSocket = default(TcpClient);
    Thread listen = new Thread(listenClients);
    listen.Start();

```