0

********平台:在 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);}
}
};
}

这里有什么问题...?

4

4 回答 4

1

可能是因为您创建的线程在默认安全上下文中执行,而不是在主线程的安全上下文中执行?

有关提示,请参阅ExecutionContext 上的文档。您可以在线程上设置 ExecutionContext 并重试。

于 2009-05-27T22:22:36.770 回答
1

你有没有从你的线程中调用 CoInitialize ?

它返回什么错误代码?

于 2010-01-22T23:13:46.840 回答
1

Shell 函数仅适用于 STA 线程,而 .NET 线程默认为 MTA。您可以将线程设置为使用单单元线程:

th->SetApartmentState(ApartmentState::STA);
th->Start();
于 2010-01-22T23:16:29.200 回答
0

我不知道为什么会这样,但是您尝试过其他线程方法吗?比如 BackgroundWorker 组件或 ThreadPool.QueueUserWorkItem?错误是否仍然发生?

于 2009-05-27T06:33:29.797 回答