我在使用 Windows 窗体应用程序的 C++/CLI 中遇到了一些令人沮丧的问题。
所以问题是我必须使用 WebClient istance 从网络服务器下载文件。通常我使用 DownloadFile 而不是 DownoadFileAsyn,但如果我想显示一个显示下载文件进度的进度条,我必须使用 DownloadFileAsyn。那么我怎么能等到下载完成呢?
代码是:
ref class Example{
private:
static System::Threading::ManualResetEvent^ mre = gcnew System::Threading::ManualResetEvent(false);
public:
void Download();
void DownloadFileCompleted(Object^ sender, System::ComponentModel::AsyncCompletedEventArgs^ e);
};
void Example::Download(){
WebClient^ request = gcnew WebClient;
request->Credentials = gcnew NetworkCredential("anonymous", "anonymous");
request->DownloadFileCompleted += gcnew System::ComponentModel::AsyncCompletedEventHandler(this,&FileCrypt::DownloadFileCompleted);
request->DownloadFileAsync(gcnew Uri("ftp://ftp...."+remote_path),remote_file,mre);
mre->WaitOne();
/*
BLOCK OF INSTRUCTIONS THAT I WANT TO RUN AFTER THE FILE DOWNLOAD IS COMPLETED
*/
}
void Example::DownloadFileCompleted(Object^ sender, System::ComponentModel::AsyncCompletedEventArgs^ e){
MessageBox::Show("COMPLETED");
mre->Set();
}
因此,当下载完成时,程序停止运行,并且在 mre->WaitOne() 指令之后不会运行上面编写的指令块。DownloadFileCompleted() 没有执行,实际上甚至显示了消息框。
有任何想法吗?我已经搜索过这个问题,很多人都遇到过,但仅限于 c#。而且我刚刚将解决方案从c#“翻译”到c++。但它不起作用...