Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/149.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 等待下载文件异步与手动重置事件c++/cli_C++_.net_Command Line Interface_Manualresetevent_Downloadfileasync - Fatal编程技术网

C++ 等待下载文件异步与手动重置事件c++/cli

C++ 等待下载文件异步与手动重置事件c++/cli,c++,.net,command-line-interface,manualresetevent,downloadfileasync,C++,.net,Command Line Interface,Manualresetevent,Downloadfileasync,我在使用windows窗体的C++/CLI应用程序中遇到了一个小小但令人沮丧的问题 所以问题是,我必须使用WebClient istance从Web服务器下载一个文件。通常我使用DownloadFile而不是DownloadFileAsyn,但是如果我想显示显示下载文件进度的进度条,我必须使用DownloadFileAsyn。那么,我怎样才能等到下载过程完成呢 代码是: ref class Example{ private: static System::Th

我在使用windows窗体的C++/CLI应用程序中遇到了一个小小但令人沮丧的问题

所以问题是,我必须使用WebClient istance从Web服务器下载一个文件。通常我使用DownloadFile而不是DownloadFileAsyn,但是如果我想显示显示下载文件进度的进度条,我必须使用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()不会执行,事实上甚至会显示messagebox


有什么想法吗?我已经研究过这个问题,很多人都有过,但只有在c#中。我刚刚把“C”的解决方案翻译成C++。但它不起作用…

您不能等待,这会导致死锁。在主线程空闲并重新进入dispatcher循环之前,DownloadFileCompleted()方法无法运行。但它不是空闲的,它被困在WaitOne()调用中。因此,该方法无法运行,并且无法设置MRE。这反过来会导致WaitOne()永远无法完成。你的程序永远无法恢复的致命拥抱。一个标准的线程错误

不清楚您为什么要等待,只是发布的WaitOne()调用毫无意义。你可以简单地删除它,一切正常。在您的实际程序中,可能后面还有一些代码,您必须将这些代码移到DownloadFileCompleted()方法中


显示UI的线程的一般编程规则适用于此处。它永远睡不着,也永远挡不住。这样做会使UI无响应,并显著增加死锁的可能性。UI是事件驱动的,例如由用户移动鼠标或按键触发的事件。触发事件时运行的代码只能在线程不执行任何其他操作时运行。下载完成也被视为一个事件。

谢谢您的回复…所以您告诉我尝试另一种方式来做我想做的事情?我给出了非常明确的提示,我不清楚为什么您不清楚。删除WaitOne()调用,必要时移动代码。除非你的代码片段在某种程度上与你的真实代码有很大的不同,我猜不出来,否则就不需要更多了。