правильный способ прервать заблокированный поток

Я создаю сервер с TCP-соединением. TCP-соединение запускается в собственном потоке в течение неопределенного времени. Есть ли хороший шаблон, позволяющий безопасно завершить работу TcpListener и клиента, а также потока? Ниже то, что у меня есть на данный момент.

private volatile bool Shudown;

void ThreadStart1()
{
    TcpListener listener = null;
    TcpClient client = null;
    Stream s = null;
    try
    {
        listener = new TcpListener(60000);
        client = listener.AcceptTcpClient();
        Stream s = client.GetStrea();
        while(!Shutdown)  // use shutdown to gracefully shutdown thread.
        {
            try
            {
                string msg = s.ReadLine();  // This blocks the thread so setting shutdown = true will never occur unless a client sends a message.
                DoSomething(msg);
            }
            catch(IOException ex){ } // I would like to avoid using Exceptions for flow control
            catch(Exception ex) { throw; }
        }
    }
    catch(Exception ex)
    {
        LogException(ex);
        throw ex;
    }
    finally
    {
        if(listener != null) listener.Close();
        if(s != null) s.Close();
        if(client != null) client.Close();
    }
}
5
задан Neal 27 November 2011 в 16:13
поделиться