开发者

How to pause a thread and resume it when needed?

everyone.

I have a problem and hope someone can help me acomplish this task.

I've created a Thread to Listen for Socket connections and when a client connects, the Thread keeps listening and I want it to stop listening until the client disconnects.

But I'm unable to figure it out, yet.

Here is the Listening Method:

/// <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);开发者_JS百科
            }
            catch (Exception e)
            {
                debugmsg("ERROR: " + e.Message);
            }                    
        }
        catch (ThreadAbortException e)
        {
            debugmsg("ABORTED!" + e.Message);
            Listener.Stop();
        }
    }
    debugmsg("end of listening");

    Listener.Stop();            
}

Anyone?

Thanks.


You should look at WaitHandle class. See example of usage at http://msdn.microsoft.com/en-us/library/system.threading.waithandle.aspx


aren't there any async methods for this that would make this problem much simpler? here's the async BeginAcceptSocket on msdn and it also features a very well documented example.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜