2011-10-10 54 views
0

您好我正在尝试使用TPL与表达式的行为创建缩略图,但我试图访问File.OpenRead(uriSource)行上的另一个线程异常。我试图将一个UI线程的参数传递给一个后台任务的线程,导致我认为的错误......我该如何解决这个问题?将参数传递到任务的操作委托结果是例外

Task.Factory.StartNew(() => RenderThumb(UriSource)).ContinueWith((bs) => 
     {....}, TaskScheduler.FromCurrentSynchronizationConext()); 

private BitmapSource RenderThumb(string uriSource) 
    { 

     Stream imageStream = File.OpenRead(uriSource); 
     ... 
     return bitmapSource; 
    } 
+0

我们的水晶球今天似乎出现故障。你介意用你得到的确切例外更新你的问题吗? –

回答

0

可能是问题在于访问UriSource,因为它是依赖项属性。试试这个:

string uriSource = UriSource; 

Task.Factory.StartNew(() => RenderThumb(uriSource)).ContinueWith((bs) => 
     {....}, TaskScheduler.FromCurrentSynchronizationConext()); 
0

只要从任何地方打电话TaskScheduler.FromCurrentSynchronizationConext()是不够的。确保调用线程是UI,并且在调用此代码时已存在于UI调度程序中,即Window_Load()/ Button_Click()等事件处理程序是调用此代码的最佳位置。

Task.Factory.StartNew(() => RenderThumb(UriSource)).ContinueWith((bs) =>   {....}, TaskScheduler.FromCurrentSynchronizationConext()); 

现在你可以假设ICommand.Execute()应该没问题,但他们可能会导致一个问题,如果命令本身是在不同的线程就像一个后台工作创造。

0

我想这和它解决了这个问题,不知道这是做它的正确方法...

Task.Factory.StartNew((s) => RenderThumb(s as String), UriSource).ContinueWith((bs) => 
     {...}, TaskScheduler.FromSynchronizationContext());