2

我正在尝试异步获取目录中文件的缩略图。除 PDF 之外的所有文件似乎都可以异步工作。

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

所有其他文件都正确返回。但是,如果我再次调用所有这些代码 if image.source == null 那么它工作正常。

在 Hans Passant 回答后编辑我的工作代码

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

谢谢!

4

0 回答 0