在套接字读取之前替代Thread.Sleep()

时间:2011-01-27 12:58:54

标签: c# winforms sockets ftp network-programming

我正在使用此FtpClient库从WinForms应用程序连接到大型机。我正在使用thread.Sleep让线程在开始读取之前等待响应,否则它会冻结。有替代方法吗?

public void Login() 
{
    if (this.loggedin) this.Close();

    Debug.WriteLine("Opening connection to " + this.server, "FtpClient");

    IPAddress addr = null;
    IPEndPoint ep = null;

    try
    {
        this.clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        addr = Dns.Resolve(this.server).AddressList[0];
        ep = new IPEndPoint(addr, this.port);
        this.clientSocket.Connect(ep);
    }
    catch (Exception ex)
    {
        // doubtfull
        if (this.clientSocket != null && this.clientSocket.Connected) this.clientSocket.Close();

        throw new FtpException("Couldn't connect to remote server", ex);
    }

    **Thread.Sleep(4000);**
    this.readResponse();
    ...
}

private void readResponse()
{
    this.message = "";
    this.result = this.readLine();

    if (this.result.Length > 3)
        this.resultCode = int.Parse(this.result.Substring(0, 3));
    else
        this.result = null;
}

private string readLine()
{
    while (true)
    {
        this.bytes = clientSocket.Receive(this.buffer, this.buffer.Length, 0);
        this.message += ASCII.GetString(this.buffer, 0, this.bytes);

        if (this.bytes < this.buffer.Length) break;
    }

    string[] msg = this.message.Split('\n');
    if (this.message.Length > 2)
    {
        this.message = msg[msg.Length - 2];
        try { response = msg[msg.Length - 3]; }
        catch { }
    }
    else
    {
        this.message = msg[0];
    }

    if (this.message.Length > 4 && !this.message.Substring(3, 1).Equals(" ")) return this.readLine();

    if (this.verboseDebugging)
    {
        for (int i = 0; i < msg.Length - 1; i++)
        {
            Debug.Write(msg[i], "FtpClient");
        }
    }
    return message;
}

public void sendCommand(String command)
{
    if (this.verboseDebugging) Debug.WriteLine(command, "FtpClient");

    Byte[] cmdBytes = Encoding.ASCII.GetBytes((command + "\r\n").ToCharArray());
    clientSocket.Send(cmdBytes, cmdBytes.Length, 0);
    this.readResponse();
}

3 个答案:

答案 0 :(得分:4)

使用异步编程模型:

socket.BeginConnect(ep, new AsyncCallback(Connected), socket);

void Connected (IAsyncResult result)
{
    var socket = (Socket)result.AsyncState;

    // do the stuff

    socket.EndConnect(result);
}

答案 1 :(得分:0)

是的,如果您可以使用.NET 4.0,则可以使用任务API。

阅读本文后,您可以了解更多信息:http://www.codethinked.com/post/2010/01/25/NET-40-and-SystemThreadingTasks.aspx

它为您提供了一种创建流程的方法,在该流程中,任务等待上一个任务结束。看一看!

答案 2 :(得分:0)

Thread.Sleep()确实是一种不好的做法。

如果您确实在使用FTP客户端,请使用FtpWebRequest BeginGetResponse(asynccallback, object)

并传递readResonse作为回调。当响应准备好时,它将被准确调用。