【问题标题】:Passing parameter into Task's Action delegate result in exception将参数传递给 Task 的 Action 委托会导致异常
【发布时间】:2011-10-11 11:00:55
【问题描述】:

您好,我正在尝试使用具有表达式行为的 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;
    }

【问题讨论】:

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

标签: c# wpf task-parallel-library


【解决方案1】:

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

string uriSource = UriSource;

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

【讨论】:

    【解决方案2】:

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

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

    现在您可能认为ICommand.Execute() 应该没问题,但如果命令本身是在不同线程(如后台工作人员)上创建的,它们可能会导致问题。

    【讨论】:

      【解决方案3】:

      我试过了,它解决了问题,不确定这是否是正确的方法......

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-07-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-17
        • 2015-07-07
        • 1970-01-01
        • 2016-09-03
        相关资源
        最近更新 更多