********平台:在Vista(终极或家庭/高级版)中它不起作用,其他操作系统(xp,windows7)它可以工作***********
我在线程中使用c ++ .net(或c#.net)清空回收站。当我这样做(没有线程)时,它可以工作。但如果线程使用它没有。请观看下面的代码段:
namespace EmptyRecycleBin_C{
enum RecycleFlags
{
SHERB_NOCONFIRMATION = 0x00000001,
SHERB_NOPROGRESSUI = 0x00000002,
SHERB_NOSOUND = 0x00000004
};
public ref class Form1 : public System::Windows::Forms::Form{
[DllImport("Shell32.dll",CharSet=CharSet::Unicode)]
static System::UInt32 SHEmptyRecycleBin(IntPtr hwnd, String^ pszRootPath, RecycleFlags dwFlags);
private: void button1_Click(System::Object^ sender, System::EventArgs^ e)
{
Thread^ th = gcnew System::Threading::Thread(gcnew ThreadStart(this, &Form1::doEmpty));
th->Start();
//this->doEmpty(); // this line works just fine
}
private: void doEmpty()
{
try{
SHEmptyRecycleBin(IntPtr::Zero, String::Empty, RecycleFlags::SHERB_NOCONFIRMATION);
}catch(Exception^ ex)
{Diagnostics::Debug::Write(ex->Message);}
}
};
}
这里的问题是什么??
答案 0 :(得分:1)
可能是因为您创建的线程在默认安全上下文中执行,而不是在主线程的安全上下文中执行?
请参阅the doc on ExecutionContext以获取提示。您可以在线程上设置ExecutionContext并重试。
答案 1 :(得分:1)
您是否从线程中调用了CoInitialize?
它返回了什么错误代码?
答案 2 :(得分:1)
Shell函数仅适用于STA线程,默认情况下.NET线程是MTA。您可以将线程设置为使用单公寓线程:
th->SetApartmentState(ApartmentState::STA);
th->Start();
答案 3 :(得分:0)
我不知道为什么会发生这种情况,但您是否尝试过其他线程方法?比如BackgroundWorker组件或ThreadPool.QueueUserWorkItem?错误是否仍然发生?