0
Answer

Threads and BeginReceive

Bill

Bill

16y
5.2k
1
I'm coding an FTP client in C#, and I'm trying to use System.Net.Socket's BeginReceive method to stop the UI from freezing when receiving data. At present, it works as it should, but whenever there's a transfer in progress (upload/download or directory listing), the UI freezes until it's complete.

I want to use BeginReceive to recive data in a different thread. This is what I have to far:
Two classes - FTP and FrmMain.
In FTP I have a delegate:

public delegate void DirListDelegate(object sender, ArrayList items);
public event DirListDelegate OnDirListComplete;

Then I have three methods:

    private void OnDataReceived(IAsyncResult asyn) {
    int bytes = dataSocket.EndReceive(asyn);
    bldBuffer.Append(Encoding.ASCII.GetString(buffer, 0, bytes));
    if(bytes < buffer.Length) {
        dataSocket.Close();
        // Trimmed code to process data into "itemsList"
        OnDirListComplete(this, itemsList);
    } else {
        WaitForData();
    }
}
private void WaitForData() {
    dataSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(OnDataReceived), null);
}
public void ListDir() {
    dataSocket = openSocket();
    //trimmed code to make server initiate transfer ("LIST -al")

    bldBuffer.Remove(0, bldBuffer.Length);
    WaitForData();
}

Then I call FTP.ListDir() from FrmMain. What should happen is the main program should be free to respond to user clicks etc and not freeze, but it's as though I'm just using Receive instead of BeginReceive.

I'm really stuck on this and I'd appreciate any help. :)