如何暂停线程并在需要时恢复

本文关键字:恢复 线程 何暂停 暂停 | 更新日期: 2023-09-27 18:06:13

每个人。

我有个问题,希望有人能帮我完成这项任务。

我创建了一个线程来侦听套接字连接,当客户端连接时,线程会一直侦听,我希望它停止侦听,直到客户端断开连接。

但是我还不能弄清楚。

以下是听力方法:

/// <summary>
/// Listen for clients
/// </summary>
private void Listen()
{
    Listener = new TcpListener(EndPoint);
    Listener.Start();
    TcpClient client;
    debugmsg("begin listening");
    ChangeState("Listening...");
    while (listen)
    {                
        if (!Listener.Pending())
        {
            debugmsg("Listener free");
            Thread.Sleep(500);
            continue;
        }
        try
        {
            // blocks until a client connects
            cliente = Listener.AcceptTcpClient();
            OnConnect(new CustomEventArgs("Client connected!"));
            ChangeState("Connected to " + cliente.Client.RemoteEndPoint.ToString());
            comunicate = true;
            try
            {
                TotalSent= 0;
                // when a client connects, start a thread to comunicate
                ThreadComunicate= new Thread(new ParameterizedThreadStart(Comunicar));
                ThreadComunicate.Name = "ComunicateThread";
                ThreadComunicate.Start(client);
            }
            catch (Exception e)
            {
                debugmsg("ERROR: " + e.Message);
            }                    
        }
        catch (ThreadAbortException e)
        {
            debugmsg("ABORTED!" + e.Message);
            Listener.Stop();
        }
    }
    debugmsg("end of listening");
    Listener.Stop();            
}

有人吗?

谢谢。

如何暂停线程并在需要时恢复

您应该看看WaitHandle类。请参阅上的用法示例http://msdn.microsoft.com/en-us/library/system.threading.waithandle.aspx

没有任何异步方法可以让这个问题变得更简单吗?这是msdn上的async BeginAcceptSocket,它还提供了一个文档很好的示例。