我如何使用TaskScheduler.FromCurrentSynchronizationContext()来解决后台线程异常的UI更新

时间:2013-02-02 18:58:37

标签: c# asynchronous .net-4.5

以下是我的问题的一个小例子,我无法从关于同一错误的其他问题中解决它。

UI Thread通过单击按钮来调用函数,该函数包含以下行:

await DataSet.AddFileAsync(String.Format("ms-appdata:///local/IMM_FACE_DB/{0}", file.Name));

AddFileAsync如下所示:

public ObservableCollection<Model> Data {get;set;}
public Task AddFileAsync(string path)
{
     return Task.Factory.StartNew((state) =>
     {
         // Here some IO and computation is done, eventually some content is added 
         // to Data. Data is also bound to a GridView and this fails.

         //I assumed that TaskScheduler.FromCurrentSynchronizationContext()
         // would solve this, but it does not.
     }, TaskScheduler.FromCurrentSynchronizationContext());
} 

正如我在上面的代码中所写,我假设TaskScheduler可以确保它在UI线程上运行。由于AddFileAsync是从Databound Buttonclick Command调用的。

我在哪里误解了什么?什么是正确的等待做到这一点。

1 个答案:

答案 0 :(得分:3)

我无法看到StartNew ......

public async Task AddFileAsync(string path)
{
  // Do some IO
  var ioResult = await DoIoAsync(path);

  // Do some computation
  var computationResult = await Task.Run(() => DoComputation(ioResult));

  // Update Data
  Data.Add(computationResult);
}