Vista only issue (.net): Calling unmanaged dll (Shell32.dll, function: SHEmptyRecycleBin) from thread

******** Platform: In Vista (Ultimate or Home / Premium) it doesn't work, other OS (xp, windows7) does ***********

I am emptying the trash using C ++. NET (or C # .net) inside a thread. When I do it directly (no thread) it works. But if you use a thread, it is not. Please see the code snippet below:

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);}
}
};
}

      

What is the problem?...

0


a source to share


4 answers


Could it be because the threads you create are running in the default security context and not in the security context of the main thread?



See the doc at ExecutionContext for a hint. You can set the ExecutionContext to your thread and try again.

+1


a source


Have you called CoInitialize from your thread?



What error code is being returned?

+1


a source


The wrapper functions only work with STA threads, and .NET threads are the default MTA. You can set the thread for single threaded threads:

th->SetApartmentState(ApartmentState::STA);
th->Start();

      

+1


a source


I don't know WHY this is happening, but have you tried other streaming methods? For example the BackgroundWorker component or ThreadPool.QueueUserWorkItem? Is the error being executed?

0


a source







All Articles