I want to use the .NET-FTP Libary (http://netftp.codeplex.com). The libary offers BeginOpenRead(string,AsyncCallback,object) to download the contents using the Asynchronous Programming Model. My implementation of the Callback is basically the same as the example:
static void BeginOpenReadCallback(IAsyncResult ar) {
FtpClient conn = ar.AsyncState as FtpClient;
try {
if (conn == null)
throw new InvalidOperationException("The FtpControlConnection object is null!");
using (Stream istream = conn.EndOpenRead(ar)) {
byte[] buf = new byte[8192];
try {
DateTime start = DateTime.Now;
while (istream.Read(buf, 0, buf.Length) > 0) {
double perc = 0;
if (istream.Length > 0)
perc = (double)istream.Position / (double)istream.Length;
Console.Write("\rTransferring: {0}/{1} {2}/s {3:p} ",
istream.Position.FormatBytes(),
istream.Length.FormatBytes(),
(istream.Position / DateTime.Now.Subtract(start).TotalSeconds).FormatBytes(),
perc);
}
}
finally {
Console.WriteLine();
istream.Close();
}
}
}
catch (Exception ex) {
Console.WriteLine(ex.ToString());
}
finally {
m_reset.Set();
}
}
After the work of the async Method is completed, it would be great if a Completed event is fired (by the thread that started the asynchronous method in order to get no problems with the UI) to pass the results to the Main-Thread. Just like BackgroundWorker does (using RunWorkerCompleted).
How can I realize this?