2

I am trying to get the thumbnails for files in a directory asynchronously. All files except PDFs seem to work async.

if (System.IO.File.Exists(filePath))
{
    var task = await Task.Factory.StartNew(async () =>
    { 
         using(ShellFile shellFile = ShellFile.FromFilePath(filePath))
         {
             ImageSource source = shellFile.Thumbnail.MediumBitmapSource;
             source.Freeze();
             return source;
         }
    });
    image.Dispatcher.Invoke(() => image.Source = task.Result);
}

All other files return correctly. However, if I call all of this code a second time if image.source == null then it works fine.

edit My working code after Hans Passant's answer

var thread = new Thread(() =>
{
    using(ShellFile shellFile = ShellFile.FromFilePath(filePath))
    {
         ImageSource source = shellFile.Thumbnail.MediumBitmapSource;
         source.Freeze();
    }
    image.Dispatcher.Invoke(() => image.Source = source);
});

thread.SetApartmentState(ApartmentState.STA);
thread.Start();

Thanks!

KenWin0x539
  • 329
  • 3
  • 8
  • The task runs on a thread that is very unfriendly to the kind of files that use a shell extension to generate their thumbnail. Like pdfs. They need an STA thread. You can find one [here](http://stackoverflow.com/a/21684059/17034). – Hans Passant Jan 19 '15 at 21:55
  • @HansPassant if you put this in an answer I'll accept it. Regardless, thanks for the help. I'll edit my question to show my working code. – KenWin0x539 Jan 20 '15 at 14:00
  • A hard requirement for an STA thread is that it must pump a message loop. You might get away with not doing this, you know you didn't if a user of your program reports a deadlock. – Hans Passant Jan 20 '15 at 15:00

0 Answers0